使用PDO插入数据库

时间:2012-05-03 02:38:13

标签: php pdo

我正在尝试将数据插入我服务器上的数据库中。

要连接到我的数据库,我有以下代码:

<?php
$host = "/homes/49/jc192699/public_html/dbase/";
$database = "EduPro.db";
$dbhandle = new PDO("sqlite:".$host.$database);

try {
    $dbhandle = new PDO("sqlite:".$host.$database);

} catch (PDOException $e) {

echo 'Connection failed: ' . $e->getMessage();
}
?> 

这一切都很好!我已将其包含在我的代码中,因此不是问题。

以下是我将数据插入数据库的代码:

<?php

$sql = "INSERT INTO USERS (`userName`, `password`) VALUES (`test, `testy`)";
  if ( $fetched = $dbhandle->query($sql)){
  $fetched->execute(PDO::FETCH_BOTH);
  echo "Success!";
  }

  else {
echo "Fail.";
}

?>

由于某种原因,它没有将数据插入数据库。我知道SQL语句100%正确,因为我在其他地方测试过它。

任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:5)

您正在打开两个数据库连接。将您的代码更改为

$host = "/homes/49/jc192699/public_html/dbase/";
$database = "EduPro.db";
try {
    $conn = new PDO("sqlite:".$host.$database);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

您不应该在查询中使用反引号而不是单引号。并且列也不应该有任何引号。

try {
    $sql = "INSERT INTO USERS (userName, password) VALUES ('test', 'testy')";
    $sth = $conn->query($sql);
} catch(PDOException $e) {
    echo $e->getMessage();
}

获取您需要使用此记录的记录

try {
    $sth = $conn->query('SELECT * FROM USERS');
    $rows = $sth->fetchAll(PDO::FETCH_ASSOC);
    //$rows contains the fetched records in an associative array
    var_dump($rows);
} catch(PDOException $e) {
    echo $e->getMessage();
}

在此处了解有关PDO的更多信息http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

答案 1 :(得分:1)

你为什么回头看这些价值?试试单引号:

$sql = "INSERT INTO USERS (userName, password) VALUES ('test', 'testy')";

另外,请检查您的PHP错误日志,它可能会给您一些见解。

根据docs,我认为您必须使用exec() vs query()来执行非选择查询,例如插入,更新和删除。如果您打算将变量传递到$sql变量,那么您还应该阅读prepare

答案 2 :(得分:0)

以下是一些语法规则:

必须在PHP中引用SQL查询 必须引用SQL查询中的字符串值 不得引用数字值 不能引用单词NULL

<?php
    if (!defined('DB_SERVER')) define('DB_SERVER', 'localhost');
    if (!defined('DB_USER')) define('DB_USER', 'xxx');
    if (!defined('DB_PASSWORD')) define('DB_PASSWORD', 'xxx');
    if (!defined('DB_TABLE')) define('DB_TABLE', 'xxx');


    // The procedural way
    $mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
    $mysqli->set_charset("utf8");
    $mysqli->query("SET NAMES 'utf8'");
    if (mysqli_connect_errno($mysqli)) {
        trigger_error('Database connection failed: '  . mysqli_connect_error(), E_USER_ERROR);
    }

    $pid = mysqli_real_escape_string($mysqli, $_GET['pid']); 
    $lvmID = mysqli_real_escape_string($mysqli, $_GET['lvmID']); 
    $in = mysqli_real_escape_string($mysqli, $_GET['in']);

    $query = "
                SELECT r.*, lvm.luchtvaartmaatschappijID
                FROM tbl_random r

                LEFT JOIN tbl_luchtvaartmaatschappij lvm
                ON r.img_lvm = lvm.IATAcode

                WHERE r.img_nmr ='$in'
                AND lvm.luchtvaartmaatschappijID = '$lvmID'
                AND r.randimgID != '$pid'
                LIMIT 6";

    $result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: 
    $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

    $row = mysqli_fetch_assoc($result);

    mysqli_close($mysqli);

    ?>

    <?php
        $items_in_row = 3 ;
        $index = 0 ;
    ?>

        <table width='100%' cellspacing='5' border='0'>
          <tr>

        <?php
        while($row = mysqli_fetch_assoc($result)){ 
          $index++ ; ?>
          <td style="text-align: center" width='375'>       

             <a href='http://globe-trekking.com/vg/home/details.php?pid=<?php echo $row['randimgID'];?>&lvmID=<?php echo $row['luchtvaartmaatschappijID'];?>&in=<?php echo $row['img_nmr'];?>'> <img src='http://globe-trekking.com/vg/img/random/<?php echo $row['img_lvm'];?>/<?php echo $row['img_file'];?>' width='345'></a> 


            <br>
          </td>
        <?php if ($index%$items_in_row == 0){ ?>
          </tr>
          <tr>
        <?php }
        } ?>
        </tr>
        </table>

然后用您的变量绑定值,它将起作用

答案 3 :(得分:0)

为了更好地将数据库数据插入数据库中,我相信您的代码应该看起来像这样。

// First make your Database connections like so.
$host = "/homes/49/jc192699/public_html/dbase/";
$database = "EduPro.db";
try {
    $conn = new PDO("sqlite:".$host.$database);
} catch (PDOException $e) {
    echo 'Connection error: ' . $e->getMessage();
}

//then next we make the data insertion using a prepared statement.
// Try to insert the data to the database

try {
    $username = "test";
    $password = "testy";

    $sql = "INSERT INTO USERS (userName, password) VALUES ('test', 'testy')";
    $sth = $conn->query($sql);

    $stmt = $db->prepare("INSERT INTO usersdata (userName, password) VALUES (:uname, :pass)");
    $stmt->bindParam(':uname', $username);
    $stmt->bindParam(':pass', $password);
    $stmt->execute();

    echo "Data inserted "; //Just get a success message

} catch(PDOException $e) {
    echo $e->getMessage();
}