INSERT query is failing in PHP

Lou

I'm sure it's a kickself-obvious typo, but I can't see it. I'm trying to INSERT data taken from a HTML form using POST into a MySQL database using PHP. The POST works successfully, but the query fails; I've checked the table to make sure nothing new has been inserted.

Here's the PHP code intended to run the query:

if ($_POST) {
    $username = "root";
    $password = "root"; //ssh don't tell
    $hostname = "localhost";

    $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
    $dbname = "asoiaf";
    $tablename = "charlist";

    $id = '3';
    $bookIntroduced = $_POST['bookIntroduced'];
    $pageIntroduced = $_POST['pageIntroduced'];
    $forename = $_POST['forename'];
    $surname = $_POST['surname'];
    $oldSurname = $_POST['oldSurname'];
    $alias = $_POST['alias'];
    $title = $_POST['title'];
    $pageIntroduced = $_POST['regnalNumber'];

    // Below is the query that fails to execute.

    $query = "INSERT INTO $tablename (
            $id, $bookIntroduced, $pageIntroduced, $title, $forename, $surname, $oldSurname, $alias, $regnalNumber
            )";

    mysql_query($query) or die("Nah, I don't feel like being helpful.");

    mysql_close($dbhandle);
}

And here is the structure of the table given by the DESCRIBE command:

enter image description here

Can anyone help me to identify the problem?

Also, if it wasn't clear, I'm new to PHP and SQL.

Dave Morrissey

Doing a SQL query like this is bad practice in many ways, not least because it's extremely fragile and insecure, but I think it will work if you add VALUES and quote the strings.

$query = "INSERT INTO $tablename VALUES (
        '$id', '$bookIntroduced', '$pageIntroduced', '$title', '$forename', '$surname', '$oldSurname', '$alias', '$regnalNumber'
        )";

I advise against doing this though, and I'm giving this answer just because it's the shortest path to working code. Always name your table and columns (INSERT INTO mytable (col1, col2) VALUES (:val1, :val2)), and use prepared statements with mysqli.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related