GhostRider
GhostRider

Reputation: 2170

Prepared statements in mysqli not working

Can someone explain to me why this isn't working. Trying to convert to prepared statements as per the advice of everybody but get stuck right at the beginning...the connection is fine and it returns no message, but there is no entry into my table (called nametable)

<?php
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "fidelio";
 $dbname = "test";
 $con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
 if(mysqli_connect_errno()) {
 die("Database connection failed: " . 
     mysqli_connect_error() . 
     " (" . mysqli_connect_errno() . ")");
   }

$query = "INSERT INTO nametable (fname, lname) values (?,?)";
$stmt = mysqli_prepare($con, $query);
$firstName = "simon";
$lastName = "morris";
mysqli_stmt_bind_param($stmt,"ss",$firstname, $lastname);
mysqli_stmt_execute($stmt);
printf("Error: %s.\n", $stmt->error);
$stmt->close();
?>

I added the last 2 lines and the error that comes back is

Error: .

This works just fine but the prepared statements do not....anyone know why?

  $sql="INSERT INTO nametable (fname, lname)
  VALUES ('$firstName', '$lastName')";
   if (!mysqli_query($con,$sql))
{
   die('Error: ' . mysqli_error($con));
 }

Upvotes: 4

Views: 1176

Answers (1)

echo_Me
echo_Me

Reputation: 37233

try this

    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "fidelio";
    $dbname = "test";

    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

     $firstName = "simon";
     $lastName = "morris";
          if ($stmtb = $mysqli->prepare("INSERT INTO nametable (fname, lname) values (?,?)")) {
              $stmtb->bind_param('ss',$firstName, $lastName); 
              $stmtb->execute(); 
           }else {printf("Prepared Statement Error: %s\n", $mysqli->error);}

Upvotes: 2

Related Questions