-2

When I try to change the code from the first block to second block, I get an error message saying it returned false. This is always how I use prepared statements for all the other methods (delete, insert, like). I believe the while loop is causing the issue.

This code below code works (but probably not SQLI injection proof):

$id=$_GET['edit'];    
$result = mysqli_query($con, "SELECT * FROM employees WHERE id=$id");

This code below gets an error message basically saying that it returned false:

$result = $con->prepare("SELECT * FROM employees WHERE id=?");
$result->bind_param('i', $_GET['edit']);
$result->execute();

while($row = mysqli_fetch_assoc($result)) {
    $id= $row['id'];
    $first_name = $row['first_name'];
    $last_name = $row['last_name'];
    $position = $row['position'];

This code below I used for a search bar and it works 100%. However, for update it gets the following error message:

Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetch_array():

while ($row = $result->fetch_array(MYSQLI_NUM))
u_mulder
  • 54,101
  • 5
  • 48
  • 64

2 Answers2

0

This is the correct answer:

if($stmt = $con->prepare("SELECT * FROM employees WHERE id=?")){
    $id=$_GET['edit']; //the ID is in the url
    $stmt->bind_param('i',$id);
    $stmt->execute();
    $result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
$id= $row['id'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$position = $row['position'];
?>

Also, after reading Example of how to use bind_result vs get_result, I concluded that using get_result is the easiest method. But that is up to the person/employer.

If this question was 'so easy', why did I get a -2? I ended up having to answer my own question after many hours of serious study. Would like a moderator or someone to explain to me how I can get 'better postings' in the future. Thanks.

-1

Try this,

$con    = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$result = $con->prepare("SELECT * FROM employees WHERE id=?");
$qryres = $result->execute('i', $_GET['edit']); //$result->bind_param('i', $_GET['edit']);
$row    = ($qryres) ? $result->fetchAll(PDO::FETCH_ASSOC) : array(); 
$con    = null;
//You can then loop over the row
Apetu Gideon
  • 136
  • 1
  • 5