I am using this code right here:
HTML code (jsonexamplecss.html):
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "adomaniname/phpselectdatawhere.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var s = 256;
var hr = new XMLHttpRequest();
hr.open("POST", "adomainname/phpselectdatawhere.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send("limit="+s);
var arr = JSON.parse(response);
var i;
var i = 0;
for(i = 0; i < arr.length; i++) {
out = arr[i].name
if (out = "0 results") {
alert("0 results");
}
}
document.getElementById("id01").innerHTML = out;
alert(out);
}
</script>
</body>
</html>
PHP code(phpselectdatawhere.php):
<?php
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM testget WHERE id='$limit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
} else {
echo "0 results";
}
$conn->close();
?>
I have a table named testget
with id, name
fields both VARCHAR
. I wrote a script in order to do these things:
The HTML script sends data to the php script via http request and in this example it sends
limit=256
.The PHP script gets the
limit=256
, puts away the number from the limit and stores$limit =256
.After that the PHP script searches if there is a
name
in the table whoseid='$limit'
and prints thename
if it exists, else it echoes 0 results. The tabletestget
has a row whereid=256
andname=JohnDoe
so it can't echo 0 results.After all this procedure the HTML scripts gets the echoed stuff and alerts them with JavaScript.
So in this case I want to have JohnDoe alerted in my HTML page but unfortunately nothing shows up. Could you please help me?
Note that the url and the database connection info are correct but as you can understand I don't want to show them.