Ocordu
Ocordu

Reputation: 5

PHP SQL Query Fails to Execute

<?php
$db = new mysqli("localhost", "HIDDEN", "HIDDEN", "HIDDEN");
if ($db->connect_error) {
    die("Failed to connect.");
}
if (isset($_POST["title"]) && isset($_POST["description"]) && isset($_POST["url"])) {
    $title = $db->real_escape_string($_POST["title"]);
    $description = $db->real_escape_string($_POST["description"]);
    $url = $db->real_escape_string($_POST["url"]);
    $sql = "INSERT INTO video (name, description, submission_date)
    VALUES ('{$title}', '{$description}', CURDATE());
    INSERT INTO video_source (video_id, url)
    VALUES (LAST_INSERT_ID(), '{$url}');";
    if ($db->query($sql) === TRUE) {
        echo "Successfully added.";
    } else {
        echo "Query failed.<br><br>Data: {$title} {$description} {$url}";
    }
} else {
    echo "Data not set.";
}
$db->close();?>

Outputs "Query failed." with the data I entered. Replacing variables such as title with constants still has the same problem. I tried the query in PHPMyAdmin and it worked fine (with constants).

It seems to be unhappy with setting the value of video_id.

Upvotes: 0

Views: 65

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34416

Anytime you're running multiple queries with MySQLi you should use multi_query():

$db->multi_query($sql)

In addition, LAST_INSERT_ID() in your second query is not returning any sort of value. If you're looking for the last inserted value of the 1st query you have to return that prior to running the second query.

Upvotes: 2

Related Questions