PHP - 无法使用PDO插入表中

时间:2016-10-14 23:25:01

标签: php mysql pdo

我使用PDO连接到我的数据库。我的问题是,由于某种原因,我无法将内容插入表中。当我使用mysqli_connect();进行连接时,我可以这样做,但这对我来说不够安全。

以下是连接数据库的代码:

<?php

$user = "root";
$pass = "";
$loggedin;
$conn = new PDO('mysql:host=localhost;dbname=login', $user, $pass);

if (!$conn) {
    die("Connection to the database failed");
}

以下是尝试将内容插入数据库的代码:

<?php

include '../dbh.php';

$first = $_POST['first'];
$last = $_POST['last'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];

if (empty($first)) {
    header("Location: ../signup.php?error=empty");
    exit();
} if (empty($last)) {
    header("Location: ../signup.php?error=empty");
    exit();
} if (empty($uid)) {
    header("Location: ../signup.php?error=empty");
    exit();
} if (empty($pwd)) {
    header("Location: ../signup.php?error=empty");
    exit();
} else {

    $sql = "SELECT uid FROM users WHERE uid='$uid'";
    $result = mysqli_query($conn, $sql);
    $uidcheck = mysqli_num_rows($result);

    if ($uidcheck > 0) {
        header("Location: ../signup.php?error=username");
        exit();
    } else {
        $sql = "INSERT INTO users (first, last, uid, pwd)
        VALUES ('$first', '$last', '$uid', '$pwd')";

        $result = mysqli_query($conn, $sql);

        header("Location: ../index.php");
    }
}

1 个答案:

答案 0 :(得分:0)

$sql = "INSERT INTO `users` (`first`, `last`, `uid`, `pwd`)
    VALUES (:first, :last, :uid, :pwd)";
$sth = $conn->prepare($sql);
$sth->bindValue(':first', $first);
$sth->bindValue(':last', $last);
$sth->bindValue(':uid', $uid);
$sth->bindValue(':pwd', $pwd);
$sth->execute();