Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a datetime with prepared statement [duplicate]

I am trying to use prepared statements to insert a datetime for a library application. Here is the code thus far:

    global $dbh;
    $query = "INSERT INTO `loan` SET
             `title` = (?), //example value - Lord of the Rings
             `description` = (?), //example value - Trilogy
             `start_date` = (?), //example value 20120701 in String datatype
             `end_date` = (?)";  //example value 20120702 in String datatype

    $statement = $dbh->prepare($query);
    $statement->bind_param("ssss", $title,$description,$startDate,$endDate);

    $statement->execute();
    print $statement->error; //to check errors
    $statement->close();

However, I cannot seem to insert this value into the row. At the same time, somehow the

            print $statement->error 

does not seem to display any error.

Any help will really do.

UPDATE:

It actually works. I was just referencing the wrong database. But I want to add a little outro for new people who chanced upon this.

  1. Remove all the comments as mentioned in the comments/answers as they will mess up your string.

  2. For DATETIME, remember to specify the datatype as String as MySQL only recognises String datatype. If you are not using prepared queries, this means you have to add '' quotes for the values.

  3. The insertion will result in the date (2012-07-01 00:00:00) format as time is not specified.

  4. Both SQL queries work. INSERT INTO tbl_name SET col_name = value or INSERT INTO tbl_name(col_name) VALUES (value) work.

like image 307
bryan.blackbee Avatar asked Nov 14 '22 02:11

bryan.blackbee


1 Answers

Try something like this:

global $dbh;
$query = "INSERT INTO loan (title, description, start_date, end_date) VALUES (?,?,?,?)"

$statement = $dbh->prepare($query);
$statement->bind_param("ssss", $title,$description,$startDate,$endDate);

$statement->execute();
print $statement->error; //to check errors
$statement->close();
like image 56
Valeh Hajiyev Avatar answered Nov 24 '22 01:11

Valeh Hajiyev