Jump to content

Trouble with a mysqli prepared statement


SpringVark

Recommended Posts

Hi again - newbie question, so advance apologies all round.

 

My connections ->prepare() method always returns false code below :(

 

<?php
    session_start();
    include '../include/db/db-open.php';
    mysqli_autocommit($mysqli, false);

    $insertPostString = "insert into posts values (null, ?, ?, now(), now(), ?, ?, 0, ?, 0, ?, ?, ?, ?, ?)";

    $stmt = $mysqli->stmt_init();
    if ($stmt = mysqli_prepare($mysqli, $insertPostString))
    {
        $stmt->bind_param(
            $_SESSION('post_postTypeId'),
            $_SESSION('post_postTypeInstanceId'),
            $_SESSION('post_dateToPublish'),
            $_SESSION('post_dateToExpire'),
            $_SESSION('post_publisherName'),
            $_SESSION('post_authorName'),
            $_SESSION('post_title'),
            $_SESSION('post_tagline'),
            $_SESSION('post_content'),
            $_SESSION('post_priorityId')
        );
        $stmt->execute();
        $stmt->close();
    }
    else
    {
        die("Could not prepare SQL statement: $insertPostString");
    }

    mysqli_autocommit($mysqli, true);
    include '../include/db/db-close.php';
?>

 

Any ideas? It has to be something obvious, I'm sure.

 

Advance thanks,

and regards.

Link to comment
Share on other sites

You are mixing Object oriented and Procedural coding. Pick one or the other.

 

For example, $stmt = mysqli_prepare() returns a bool true/false and assigns that to $stmt, but you are then trying to use $stmt as an object in $stmt->bind_param()

 

I suspect your actual problem is that $mysqli is not what you think it is, so when you use it as an object in $mysqli->stmt_init() and then use it as a link in mysqli_prepare($mysqli, $insertPostString) that it cannot work. What type is $mysqli in your connection code?

Link to comment
Share on other sites

My connection code:

$mysqli = new mysqli('localhost','root','','wpspc');

 

The reason I starting switching to procedural code was because the mysqli_autocommit($mysqli, false); statement was failing when I tried calling it the OO way (Cannot call a static method from a dynamic context, or something like that).

 

Anyway, I've now changed the prepared statement to OO without any luck:

    $insertPostString = "insert into posts values (null, ?, ?, now(), now(), ?, ?, 0, ?, 0, ?, ?, ?, ?, ?)";
    if ($stmt = $mysqli->prepare($insertPostString))
    {}

 

(the if still fails).

 

Is it possible to be doing that when I'm still calling mysqli_autocommit($mysqli, false); procedurally? I really do need a rollback option because this thing is going to be transaction critical.

 

Thanks,

d.

Link to comment
Share on other sites

I had in fact noticed the lack of a data description string before, and thus have been using it since. The code currently looks as below. It seems like a mysql error, but if I substitute values and run it in the MySql client console, it runs just fine. Is there any way to see the mySql return error in my browser? Or am I barking up the wrong tree (i.e. is the error still in my php?). Much thanks.

 

<?php
...
    if ($stmt = $mysqli->prepare($insertPostString))
    {
        $stmt->bind_param(
            'isssssssi',
            $_SESSION['post_postTypeId'],
            $_SESSION['post_dateToPublish'],
            $_SESSION['post_dateToExpire'],
            $_SESSION['post_publisherName'],
            $_SESSION['post_authorName'],
            $_SESSION['post_title'],
            $_SESSION['post_tagline'],
            $_SESSION['post_content'],
            $_SESSION['post_priorityId']
        );

        $postId = 0;
        if ($stmt->execute())  {

            $resultSet = $mysqli->query('select max(id) from posts');
            $result = $resultSet->fetch_object();
            $postId = $result->id;

            $insertWeekendReportString = "insert into reports values null, ?, ?, ? ";
            $stmt2 = $mysqli->prepare($insertWeekendReportString);
            $stmt2->bind_param('iss', $postId, $_REQUEST['reportStartDate'], $_REQUEST['reportEndDate']);

            if ($stmt2->execute()) {
                mysqli::commit();
            }
            else {
                $mysqli->rollback();
                die("Could not commit SQL statement: $insertWeekendReportString");
            }
        }
        else {
            $mysqli->rollback();
            die("Could not commit SQL statement: $insertPostString");
        }
...
?>

Link to comment
Share on other sites

A quick update:

 

I realised that my problems were most likely being caused by some of my input to mySql - and indeed I was inserting single quotes without running the content through htmlspecialchars() first.

 

However, the result when I run the code with htmlspecialchars() has not changed - it still fails when I run $stmt->execute().

 

My biggest problem is debugging it... I simply don't have the php experience to know how!?

 

Thanks for your posts thus far.

d.

Link to comment
Share on other sites

You need not escape data while using prepared statements.

 

Is there any way to see the mySql return error in my browser?

 

Yes. Add

echo $mysqli->error;

BEFORE each $mysqli->rollback();

 

[edit]

 

Also this:

            if ($stmt2->execute()) {
                mysqli::commit();
            }

 

should be

 

            if ($stmt2->execute()) {
                $mysqli->commit();
            }

 

[edit]

 

And another one: you have 10 '?' in your $insertPostString but you only bind 9 parameters.

Link to comment
Share on other sites

Thank you! The "echo $mysqli->error;" worked like a charm... and leads me to another obstacle :(

Incorrect date value: '' for column 'dateToExpire' at row 1

I want to be able to pass in a null value here. Apparently '' does not work, and neither does "null".

Let me try and leave a blank space, and get back to you here...

Link to comment
Share on other sites

For future reference. Instead of

INSERT INTO table VALUES (?,null,?)
you could use query like
[code]INSERT INTO table (column1, column3) VALUES (?,?)

 

You only need to specify columns you have data for, and all others will be inserted with default values or nulls.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.