Saturday 13 April 2019

php - mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given




I am pretty new to PHP and MySQL and I just can't figure this one out. I have searched all around the forum but haven't found an answer I can make sense of. I originally was using mysql_fetch_assoc() but I could only search numbers and I received errors when searching for letters as well. I hope I am on the right track here. Thank you in advance for all your help!



$con = mysqli_connect($hostname,$username,$password) or die ("");
mysqli_select_db($con, $dbname);

if (isset($_GET['part'])){
$partid = $_GET['part'];
$sql = 'SELECT *

FROM $usertable
WHERE PartNumber = $partid';

$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);

$partnumber = $partid;
$nsn = $row["NSN"];
$description = $row["Description"];
$quantity = $row["Quantity"];

$condition = $row["Conditio"];
}

Answer



This happens when your result is not a result (but a "false" instead).
You should change this line



$sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';



to this:



$sql = "SELECT * FROM $usertable WHERE PartNumber = $partid";


because the " can interprete $variables while ' cannot.



Works fine with integers (numbers), for strings you need to put the $variable in single quotes, like



$sql = "SELECT * FROM $usertable WHERE PartNumber = '$partid' ";



If you want / have to work with single quotes, then php CAN NOT interprete the variables, you will have to do it like this:



 $sql = 'SELECT * FROM '.$usertable.' WHERE string_column = "'.$string.'" AND integer_column = '.$number.';

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...