Chris
Chris

Reputation: 3698

Failing to properly use prepared statements with mysqli

I am learning php and mysqli,

I want to get the result of mysql query printed.
So far I have done this:

$link = mysqli_connect("host","user", "pass","db_name");
//error handling here
//printing host info here
$company_name = "ODEON";
$query = "select company from production where company = ?";
$stmt = mysqli_stmt_init($link);
if (!($stmt = mysqli_stmt_prepare($stmt, $query))){
     echo "Prepare failed: (" . $stmt->errno . ") " . mysqli_error($link);
}
var_dump($stmt); //for debugging
echo "before bind<br>";
if(!(mysqli_stmt_bind_param($stmt, "s", $company_name))){
    echo "Binding parameters failed: (" . $stmt->errno . ") " . mysqli_error($stmt);
}
echo "after bind<br>";
var_dump($stmt); //for debugging

if(!(mysqli_execute($stmt))){
    echo "Execute failed: (" . $stmt->errno . ") " . mysqli_error($stmt);  
}

printf("<hr>Results:<br>");
while($obj = mysqli_fetch_object($result)){
    printf("%s<br>", $obj->company_name);
}
mysqli_free_result($obj);
printf("<hr><br>");

mysqli_stmt_close($stmt);
mysqli_close($link);

And all I am getting is this:

Host information: host via TCP/IP
Prepare failed: (0) NULL 
Binding parameters failed: () NULL 
Execute failed: () 

What is wrong?

Upvotes: 1

Views: 249

Answers (2)

Chris
Chris

Reputation: 3698

It has been finally solved. The problem was that there weren't any errors posted when I was using localhost. So, at my php.ini file located at

/usr/local/zend/etc/php.ini

(due to installing zend framework) changed display errors to on..

The problem with the code was probably here:

$stmt = mysqli_stmt_prepare($stmt, $query)

With the first argument, which is not needed.

Upvotes: 1

hafichuk
hafichuk

Reputation: 10781

I think that the issue is with your use of mysqli_stmt_prepare

You are passing in $link however you need to be passing in the statement. You'll need to call $stmt = mysqli_stmt_init($link); and pass $stmt instead.

Snip from the PHP docs:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, 'SELECT District FROM City WHERE Name=?')) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Upvotes: 1

Related Questions