php - Beginning wit PDO, first program doesn't work

295

I began learning PDO today. This is my first program actually, and I'm stuck in the first program.

Here's a simple form which adds a single value to a database. When I click submit button, it gives Could not execute because of (The errorInfo function returns nothing)

Database Structure

Column    Type
id         int unsigned auto_increment
name       varchar(255)

fillvalues.html

<form action="fillvalues.php" method="post">
<input type="text" name="test">
<input type="submit" name="submit">
</form>

fillvalues.php

<?php

include 'dbconnector.php';
//fill values
var_dump($db);

$sql="INSERT INTO test('name') VALUES ('" . $_POST['test'] . "')";
$smt=$db->query($sql);
if(!$smt)
{
    $ei = $db->errorInfo();
    die('Could not execute because of') . $ei[2];
}
else
{
    echo "Added";
}

var_dump($smt);
var_dump($sql);

?>

dbconnector.php

<?php

try
{
    $db=new PDO("mysql:host=localhost;dbname=pdo",'root','');
}
catch(PDOException $pe)
{
    die('Could not connect to the database') . $pe->getMessage();
}
?>

Any suggestions are welcome.

255

Answer

Solution:

you have syntax error in your query. you shouldn't quote column names with apostrophe:

INSERT INTO test(name) VALUES ('" . $_POST['test'] . "')
676

Answer

Solution:

this is how your statement should be if your using

PDO for mysql

$sql="INSERT INTO test(name) VALUES(:myval)";
$smt=$db->prepare($sql);
$smt->bindParam(':myval', $_POST['test'], PDO::PARAM_STR);
$smt->execute();

People are also looking for solutions to the problem: php - Small modification to regex to make it work?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.