简体   繁体   中英

Insert a datetime with prepared statement

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.

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();

Assuming your form input for your date is a type input named "date", here is what you do. In php type

$date = $_POST['date']

$query = "INSERT INTO `loan` SET
             `title` = (?), 
             `description` = (?), 
             `start_date` = ".$date. //Insert variable here
             "`end_date` = (?)"; 

I know it's not good practice to insert a date in one single type input but I am just using this example for simplicity only. The proper way you can figure out yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM