简体   繁体   中英

Change mysql_ functions with PDO

I need to rewrite my php code with mysql_* functions with PDO so I have:

<?php

$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');

mysql_select_db('gmaestro_agro', $con); 

    mysql_select_db('gmaestro_agro', $con);
    $query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
      $query .= "'".mysql_real_escape_string($_POST['Name']) . "', ";
      $query .= "'".mysql_real_escape_string($_POST['Gender']) . "', ";
      $query .= "'".mysql_real_escape_string($_POST['Age']) . "', ";
      $query .= "'".mysql_real_escape_string($_POST['Donuts_eaten']);
      $query .= "')";
    $result = mysql_query($query);
    if($result != false) {
        echo "success!";
    } else {
        echo "an error occured saving your data!";
    }

?>

and I try to write this but with PDO function like this:

<?php


    /* Your Database Name */
    $dbname = 'gmaestro_agro';

    /* Your Database User Name and Passowrd */
    $username = 'gmaestro_agro';
    $password = 'pass';

     $stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
      $stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);



    $sql = "INSERT INTO stat(Name,
            Gender,
            Age,
            Donuts eaten
            ) VALUES (
            :Name, 
            :Gender, 
            :Age, 
            :Donuts_eaten)";

$stmt = $pdo->prepare($sql);

$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);       
$stmt->bindParam(':Gender', $_POST['gender'], PDO::PARAM_STR); 
$stmt->bindParam(':Age', $_POST['age'], PDO::PARAM_STR);
// use PARAM_STR although a number  
$stmt->bindParam(':Donuts_eaten', $_POST['Donuts_eaten'], PDO::PARAM_STR); 

$stmt->execute(); 
if($stmt != false) {
        echo "success!";
    } else {
        echo "an error occured saving your data!";
    }

    ?>

I dont get any error just nothing happend? Any idea how to solve my problem?

You are mixing up your variables, $pdo is undefined / not your database connection.

You can probably solve it by using:

 $pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

instead of:

 $stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
 $stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

And if a table or column name contains spaces, you need to quote them in backticks:

        Gender,
        Age,
        `Donuts eaten`
        ) VALUES (

But with the first change, PDO should throw an exception to show you this problem.

Edit (successful test code)

Table and data creation codes used for the successful insertion (test).

Column Donuts_eaten has been used with an underscore instead of a space.

You can base yourself on this:

Table creation codes in PHPmyadmin

Note: Change your_db_name to your Database name.

CREATE TABLE `your_db_name`.`stat` (
`Name` VARCHAR( 255 ) NOT NULL ,
`Gender` VARCHAR( 255 ) NOT NULL ,
`Age` INT NOT NULL ,
`Donuts_eaten` INT NOT NULL
) ENGINE = MYISAM 

HTML form

Note: <input type="text" name="Donuts_eaten"> - Donuts_eaten is not the same as donuts_eaten notice the lowercase d

<form action="insert.php" method="post">
Name: 
<input type="text" name="name">
<br>
Gender: 
<input type="text" name="gender">
<br>
Age: 
<input type="text" name="age">
<br>
Donuts eaten: 
<input type="text" name="Donuts_eaten">
<br>
<input type="submit" name="submit" value="Submit">
</form>

PHP/SQL

<?php
/* Your Database Name */
$dbname = 'dbname'; // change this

/* Your Database User Name and Passowrd */
$username = 'username'; // change this
$password = 'password'; // change this

$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO stat (Name,
        Gender,
        Age,
        Donuts_eaten
        ) VALUES (
        :Name, 
        :Gender, 
        :Age, 
        :Donuts_eaten)";

$stmt = $pdo->prepare($sql);

$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);       
$stmt->bindParam(':Gender', $_POST['gender'], PDO::PARAM_STR); 
$stmt->bindParam(':Age', $_POST['age'], PDO::PARAM_STR);
// use PARAM_STR although a number  
$stmt->bindParam(':Donuts_eaten', $_POST['Donuts_eaten'], PDO::PARAM_STR); 

// old execute
// $stmt->execute(); 
$stmt->execute(array(':Name' => $_POST['name'],':Gender' => $_POST['gender'],':Age' => $_POST['age'],':Donuts_eaten' => $_POST['Donuts_eaten']));
if($stmt != false) {
    echo "success!";
} else {
    echo "an error occured saving your data!";
}

?>

Original answer

You need to wrap Donuts eaten in backticks (for your column name), due to the space.

$sql = "INSERT INTO stat(Name,
        Gender,
        Age,
        `Donuts eaten`
        ) VALUES (
        :Name, 
        :Gender, 
        :Age, 
        :Donuts_eaten)";

Using spaces in column names is discouraged. Use an underscore instead for your table's column.

Also, change:

$stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

to:

$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

because you're using $pdo in $stmt = $pdo->prepare($sql);

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