0

I am connected to my database using PDO. My problem is, I can't insert stuff into the table for some reason. I could do it when I connected using mysqli_connect(); but that isn't secure enough for me.

Here is my code that connects to the database:

<?php

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

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

Here is the code that is trying to insert stuff into the database:

<?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");
    }
}
  • Higher security certainly is _not_ a reason to prefer `PDO` over `mysqli`. – arkascha Oct 14 '16 at 23:37
  • You definitely can _not_ use the `mysqli_...()` functions on an object you created using `new PDO(...)`! _Read the documentation and examples!_ A simple look into your http servers error log file would have told you that this is the issue you face. – arkascha Oct 14 '16 at 23:38
  • Your code is vulnerable to sql injection attacks. You want to read about the advantages of "prepared statements" in combination with "parameter binding". – arkascha Oct 14 '16 at 23:38
  • Both PDO and mysqli have the same security feature, which is prepared statements. But if you don't use them, you're not getting the security benefit of either of them. – Barmar Oct 14 '16 at 23:51
  • OMG typed 2 page answer and now its closed , OMG :3 – Laith Oct 15 '16 at 00:00

1 Answers1

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();
Greg
  • 129
  • 6