Can't connect to mySQL server using PDO [close

2019-08-19 06:29发布

问题:

I'm new to mySQL, and the code I used, which was working, is apparently out of date, so I switched to PDO. I tried to transfer my coding as accurately as possible from the old style to PDO, but now I can't connect and I'm sure I'm just doing something silly to mess it up.

Here's my old code which worked:

//insert.php
mysql_connect("localhost","root","root");//database connection
mysql_select_db("Menu_Items");

$name = $_POST['food'];
$order = "INSERT INTO foods
            (name)
            VALUES
            ('$name')";
//inserting data order
//declare in the order variable
$result = mysql_query($order);
if($result){
    echo("<br>Input data is succeed");
}else{
    echo("<br>Input data is fail");
}

Here's my new PDO code which is not working:

$dbc    = "mysql:host=localhost;dbname=Menu_Items";
$user   = "root";
$pass   = "root";

$pdo    = new pdo($dbc, $user, $pass);
$name   = $_POST['food'];
$insert     = "INSERT INTO foods (name) VALUES ('$name')";

$result = pdo -> query($insert);
if($result){
    echo("<br>Input data is succeed");
}else{
    echo("<br>Input data is fail");
}

Where's the problem at? Thanks.

回答1:

So as I mention in comment,

pdo -> query($insert);

should be

$pdo->query($insert);


回答2:

Try some error handling. For example:

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    foreach($dbh->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

If you had a connect error, at least you could see what the error was.



回答3:

One of the primary reasons to use PDO is that it has tools to help you avoid SQL injection. So, this:

$insert = "INSERT INTO foods (name) VALUES ('$name')";

is a big no-no. Make sure you're using a parameterized query, at the very least:

$insert = $pdo->prepare("INSERT INTO foods (name) VALUES (:name)");
$insert->bindParam(":name", $name);
$insert->execute();