0

I am trying to insert data into database using mysqli prepare statement on a localhost. Just started learning PHP after Java. Everything seems to be ok, since there are no errors being displayed.when I run it. I am using PHP version 7.4.11. It just will not insert data into database. I've been dealing with this for past 6 hours. I just can't get what's wrong with it. Here is the script

error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('scream.enabled', false);

include_once 'dbCon.php';

$first = mysqli_real_escape_string($conn, $_POST['first']);
$last =  mysqli_real_escape_string($conn, $_POST['last']);
$email =  mysqli_real_escape_string($conn, $_POST['email']);
$uid =  mysqli_real_escape_string($conn, $_POST['uid']);
$password =  mysqli_real_escape_string($conn, $_POST['password']);


$sql = "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES (?, ?, ?, ?, ?);";

$stmt = mysqli_stmt_init($conn);

if(!mysqli_stmt_prepare($stmt, $sql))
{
        echo "SQL ERROR!";

}

else
{
    mysqli_stmt_bind_param($stmt, "sssss", $first, $last, $email, $uid, $pwd);
    mysqli_stmt_execute($stmt);
}

I have also tried with backticks and diferrent approach:

$stmt = mysqli_prepare($conn, "INSERT INTO `users` (user_first, user_last, user_email,user_uid, user_pwd) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, $first, $last, $email, $user_uid, $pwd);
if(mysqli_stmt_execute($stmt)){
echo "Data finally inserted.";
}

else{
    echo "ERROR ofcourse";
}

I also tried a number of other approaches which I've found in answered questions, but it just will not work. Please help. Thank you.

dolap
  • 33
  • 5
  • 2
    Since you're using prepared statements, **do not** use `mysqli_real_escape_string()`. In fact, **never use** `mysqli_real_escape_string()` – Phil Oct 21 '20 at 22:12
  • If you're coming from Java, you might find the OOP version of the MySQLi extension more familiar, eg `$stmt = $conn->prepare($sql); $stmt->bind_param("sssss", $first, $last, $email, $uid, $pwd); $stmt->execute();` – Phil Oct 21 '20 at 22:18
  • Ok. How or what I should use instead? – dolap Oct 21 '20 at 22:18
  • I have tried OOP I have tried PDO it just will not insert data. – dolap Oct 21 '20 at 22:19
  • I didn't say OOP (or PDO) would work any better, just that you might find them more familiar. To avoid using `mysqli_real_escape_string()`, you would just use something like `$first = $_POST['first'] ?? null;` or something like that – Phil Oct 21 '20 at 22:22
  • In case you missed it, the duplicate link at the top of your question shows how to get the MySQLi extension to report errors so that you can figure out what's going wrong. – Phil Oct 21 '20 at 22:23
  • OOP indeed is much more familiar to me, I'll get back to it. Thank you very much for your time. – dolap Oct 21 '20 at 22:25
  • I missed that, Thanks. – dolap Oct 21 '20 at 22:26

0 Answers0