Saturday, 28 January 2017

php - MySQL isn't finding a specific row in a table




I just got into PHP and I want to make a simple data look up script. This is the code I am using now in an index.php file.



    $mysqlHost = 'localhost';
$mysqlUser = 'root';
$mysqlPass = 'password';
$mysqlDatabase = 'core';


$conn = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase);
if ($conn -> connect_error)
die('Connection Failed: ' . $conn -> connect_error);

$sql = 'SELECT * FROM users WHERE name = SimonM34';
$result = $conn -> query($sql);

if ($result -> num_rows > 0) {
$row = $result -> fetch_assoc();
$rawJson -> name = $row['name'];

$rawJson -> rank = $row['rank'];
$rawJson -> subrank = $row['subrank'];
$rawJson -> balance = $row['balance'];
$json = json_encode($rawJson);
echo $json;
} else {
echo 'No users found!';
}

$conn -> close();


?>


This always shows No users found but if I change the statement to SELECT * FROM users it returns {"name":"SimonM34","rank":"Guest","subrank":"None","balance":"500"} which is very weird and I cannot figure out why this happens.



Thank you


Answer



The problem is in your query:




$sql = 'SELECT * FROM users WHERE name = SimonM34';


You are comparing a string value without quotes. Replace your query with something like this:



$sql = 'SELECT * FROM users WHERE name = "SimonM34"';


That's the only problem I suppose.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...