0

So this works:

$name=mysqli_real_escape_string($conn,$_POST['name']);
$password=mysqli_real_escape_string($conn,$_POST['password']);
$sql= "SELECT password FROM Accounts WHERE username='$name';";
$result= $conn->query($sql);
$row=mysqli_fetch_assoc($result);

but this doesn't:

$name=mysqli_real_escape_string($conn,$_POST['name']);
$password=mysqli_real_escape_string($conn,$_POST['password']);
//$sql= "SELECT password FROM Accounts WHERE username='$name';";

$stmt = $conn->prepare("SELECT password FROM Accounts WHERE username=?");
$stmt->bind_param("s",$name);
$stmt->execute();
$result= $stmt->get_result();

$row=mysqli_fetch_assoc($result);
$stmt->close();

Why would the first one work, but not the second one? I have PHP 7 installed on my server. I wanna make input secure to avoid SQL injection, but prepared statements aren't working for some reason

EDIT: so using bind_param() and fetch() fixed the problem for me. But I'm still curious why get_result() didn't work. Does get_result() provide just the value selected, whereas my old $result =query() returned the entire row?

My guess is maybe the two methods return different types of data/formats?

Skilliard
  • 1
  • 1
  • After `$result= $stmt->get_result();` why this:- `$row=mysqli_fetch_assoc($result);`(object+procedure mix). check the example:-http://php.net/manual/en/mysqli-stmt.get-result.php – Alive to die - Anant Feb 09 '17 at 05:29
  • The row variable is so that I can do this: if((mysqli_num_rows($result)!=0)) { if (password_verify($password,$row["password"])) – Skilliard Feb 09 '17 at 05:31
  • `$result= $stmt->get_result();while ($row = $result->fetch_array(MYSQLI_ASSOC)) { print_r($row); }` – Alive to die - Anant Feb 09 '17 at 05:33
  • define "doesn't work". gives out an error? dies with a white screen? explodes in your face? – Your Common Sense Feb 09 '17 at 05:35
  • Sorry, I should've been more specific. I get a 500 error in my browser when I use the script involving prepared statements. code is identical in the two versions besides what I showed in the OP – Skilliard Feb 09 '17 at 05:37
  • @Skilliard use the code what i have given in comment and remove `$row=mysqli_fetch_assoc($result);` – Alive to die - Anant Feb 09 '17 at 05:38
  • Then refer to the link at the top of your question, get the *actual* error message and then google for it – Your Common Sense Feb 09 '17 at 05:48
  • It's not very descriptive, and Google leads to mixed answers. Like one returns a mysqli_object and the other returns a resultset, but it doesn't explain either of them, and I can't find any sort of comparison of the two on Google. – Skilliard Feb 09 '17 at 06:12

0 Answers0