Forum Moderators: coopster

Message Too Old, No Replies

MySQL Insert Prepared Statement Not Working

A PHP insert statement won't insert.

         

CraneWing

9:33 pm on Nov 4, 2014 (gmt 0)

10+ Year Member



Hello, I am a coding newbie. I am trying to do prepared statements on a website and am creating code for a page where a user can make posts. And this one is driving me crazy, because I can't insert into a table!

First I connect to my database, with this file, connect.inc.php:

$connect = mysqli_connect('localhost', 'admin', '', 'social_net')
or die('Could not connect to database: ' . mysqli_error());


The form that receives the user post is sending it correctly to a page called add_post.php.
[size=3]<?php

session_start();
// has function for sanitzing data
include 'includes/functions.inc.php';
// needed to connect to DB
include 'includes/connect.inc.php';
// user ID needed to be passed for query - converted to integer for convience
$id = intval($_SESSION['id']);

if (isset($_POST['make_post'])) {
$body = $_POST['user_post'];
$body = sanitize_data($body);
$date_added = date('d-M-Y g:H a');

$stmt = $connect->prepare("SELECT `first_name`, `last_name`
FROM `users` WHERE `id` = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($col1, $col2);

while ($stmt->fetch()) {
$first_name = $col1;
$last_name = $col2;
}
$stmt->close();

$added_by = $first_name . ' ' . $last_name;
$posted_to = $first_name . '\'s page';
}
echo $body . '<br>';
echo gettype($body) . '<br>';
echo $date_added . '<br>';
echo gettype($date_added) . '<br>';
echo $added_by . '<br>';
echo gettype($added_by) . '<br>';
echo $posted_to . '<br>';
echo gettype($posted_to) . '<br>';
echo $id . '<br>';
echo gettype($id) . '<br>';

$stmt2 = $connect->prepare("INSERT INTO `posts` (`body`, `date_added`,
`added_by`, `posted_to`, `user_id`) VALUES(?, ?, ?, ?, ?)");
$stmt2->bind_param('ssssi', $body, $date_added, $added_by, $posted_to, $id);
$stmt2->execute();
$stmt2->close();[/size]


The prepared statement I used is virtually identical to one that successfully inserts users into a users table. What is wrong with my query?

I have tried var_dump() and got the answer that nothing is being posted. I tried adding an error checker, and no error is being echoed. Any help is greatly appreciated.

penders

11:22 pm on Nov 4, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have tried var_dump() and got the answer that nothing is being posted. I tried adding an error checker, and no error is being echoed.


Where did you use var_dump()? What "error checker"? Error checking should be part of your code - and there doesn't seem to be any? prepare(), bind_param() and execute() each return (bool)false on failure, so which part is failing?

You are missing a space after "VALUES" - although I don't think that is it.

What error_reporting level is PHP set at? Enable full error reporting whilst developing, for example:
error_reporting(-1);


Welcome to WebmasterWorld :)

CraneWing

11:37 pm on Nov 4, 2014 (gmt 0)

10+ Year Member



I put var_dump($stmt) after $stmt2->execute();

The stmtm2 = prepare... originally had "or die(mysqli_error()" attached to the end.

penders

11:14 am on Nov 5, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I put var_dump($stmt) after $stmt2->execute();


Presumably you mean var_dump($stmt2)? (Although you should probably be reusing the variables here.) And this output "bool(false)"?

The stmtm2 = prepare... originally had "or die(mysqli_error()" attached to the end.


"stmtm2" should be "$stmt2"? And presumably this did not fail with an error?

CraneWing

2:10 pm on Nov 5, 2014 (gmt 0)

10+ Year Member



Here is the final error checking code I inserted into the query, based on suggestions in a post in Stack Overflow([stackoverflow.com ]):

[size=3]$stmt2 = $connect->prepare("INSERT INTO `posts` (`body`, `date_added`,
`added_by`, `posted_to`, `user_id`) VALUES(?, ?, ?, ?, ?)");
if (false == $stmt2) {
die('prepare() failed ' . htmlspecialchars($stmt2->error));
}

$rc = $stmt2->bind_param('ssssi', $body, $date_added, $added_by, $posted_to, $id);
if (false == $rc) {
die('bind_param() failed ' . htmlspecialchars($stmt2->error));
}

$stmt2->execute();
if (false == $rc) {
die('execute() failed ' . htmlspecialchars($stmt2->error));
}

var_dump($stmt2);
$stmt2->close();
}[/size]

CraneWing

2:14 pm on Nov 5, 2014 (gmt 0)

10+ Year Member



Here is the final error checking code I inserted into the query, based on suggestions in a post in Stack Overflow([stackoverflow.com ]):

[size=3]$stmt2 = $connect->prepare("INSERT INTO `posts` (`body`, `date_added`,
`added_by`, `posted_to`, `user_id`) VALUES(?, ?, ?, ?, ?)");
if (false == $stmt2) {
die('prepare() failed ' . htmlspecialchars($stmt2->error));
}

$rc = $stmt2->bind_param('ssssi', $body, $date_added, $added_by, $posted_to, $id);
if (false == $rc) {
die('bind_param() failed ' . htmlspecialchars($stmt2->error));
}

$stmt2->execute();
if (false == $rc) {
die('execute() failed ' . htmlspecialchars($stmt2->error));
}

var_dump($stmt2);
$stmt2->close();
}[/size]


The resultant error message showed that I was using incorrect date format for MySQL, which defaults to YYYY-MM-DD. I wanted the date and time to be something like 05 Nov 2014 8:18 a.m.

I had the option of using PHP's date() function and making the date field in my database a VARCHAR string, or doing MySQL date formatting, or date() and strtotime(). I decided to just represent the date as a string, as it is meant as a permanent timestamp on the user post.

penders

3:22 pm on Nov 5, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Ah OK, thanks for the feedback.

To be honest you are usually better off using a proper date (or datetime) field in the database as it will usually make the SQL easier later - allowing you to make direct use of the large number of built-in MySQL date/time functions.

$date_added = date('d-M-Y g:H a');


Once you have a real date/time stored in the database, then you display it however you like.

For a "date added" field (when the record was inserted into the database), you can make the current timestamp a default for this field so you don't actually need to explicitly specify it in the INSERT statement.