PDO not throwing errors - php

I have the following code to insert a new record in a database:
<?php
require('comune.php');
$nome = $_POST['nome'];
$username = $_POST['username'];
$segreto = $_POST['password'];
$password = md5($segreto);
$validity = $_POST['validity'];
$ruolo = $_POST['ruolo'];
$funzione = $_POST['funzione'];
list($giorno, $mese, $anno) = explode('/', $validity);
$validity = implode('-', array($anno, $mese, $giorno));
try {
$sql = "INSERT into utenti "
. "(nome,username,segreto,password,validity,ruolo,funzione) "
. "VALUES ('$nome', '$username', '$segreto', '$password', '$validity', '$ruolo', '$funzione')";
$s = $pdo->prepare($sql);
$s->execute();
} catch (PDOException $e) {
$message = "ko";
}
$message = "ok";
//echo $sql;
echo $message;
?>
The issue I am facing is that, even if the query returns an error, $message is "ok". What am I doing wrong??

change your code to
$sql = "INSERT into utenti (nome,username,segreto,password,validity,ruolo,funzione) "
. "VALUES (?,?,?,?,?,?,?)";
$s = $pdo->prepare($sql);
$s->execute([$nome, $username, $segreto, $password, $validity, $ruolo, $funzione]);
echo "ok";
you will have either ok or informative error message

Related

What is the mistake in this PHP code?

I have a user registration system but its empty. This is the script I use in forum.modxpertz.tk. It worked at first but it shows nothing now. Here is the code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn,'login');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT userid FROM login";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$reguserid=$row["userid"];
}
$userid = mysqli_real_escape_string($conn, $_POST['userid']);
$pswrd = mysqli_real_escape_string($conn, $_POST['pswrd']);
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$token = rand('122332344','922332344');
$url = array('forum.modzexpertz.tk/verify.php#',$token);
$post= join($url);
if($userid!=$reguserid){
$sql = "INSERT INTO login(fname, lname, userid, pswrd, gender)VALUES('$fname', '$lname', '$userid', '$pswrd', '$gender')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}else {
echo "Failed to Register.";
}} else {
echo "A user with the email youve provided has already been registered.";
}}
$conn->close();
?>
I know only little about PHP and jQuery.
Please try below code :
<?php
$servername = "localhost";
$username = "root";
$pswrd = "";
$db = "login";
$conn = mysqli_connect($servername,$username,$pswrd, $db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$table = 'login';
if(#mysqli_num_rows(mysqli_query($conn, "SELECT NULL FROM `$table` WHERE userid='".$_POST['userid']."'")) > 0){
$error = "1";
echo "user with same userid is already exist";
}
if(isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['gender']) && isset($_POST['userid']) && isset($_POST['pswrd']) && $_POST['fname']!="" && $_POST['lname']!="" && $_POST['gender']!="" && $_POST['userid']!="" && $_POST['pswrd']!="")
{
if($error==''){
$ins['fname'] = mysqli_real_escape_string($conn, $_POST['fname']);
$ins['lname'] = mysqli_real_escape_string($conn, $_POST['lname']);
$ins['gender'] = mysqli_real_escape_string($conn, $_POST['gender']);
$ins['userid'] = mysqli_real_escape_string($conn, $_POST['userid']);
$ins['pswrd'] = mysqli_real_escape_string($conn, $_POST['pswrd']);
$insertsql = "INSERT INTO `$table` (fname, lname, gender, userid, pswrd) VALUES ('".$ins['fname']."','".$ins['lname']."','".$ins['gender']."','".$ins['userid']."','".$ins['pswrd']."')";
#mysqli_query($conn, $insertsql);
//echo $insertsql; exit;
echo "Success";
}
}else{
echo "Please enter required parameters";
}
mysqli_close($conn);
?>

What is wrong in these mysqli prepared statements?

I'm trying to make a registration script using PHP with Mysql database. The insertion cannot be done. If I register with an email-id which is already in the database, it is working fine. But, the script fails to insert new entries. It is returning 'bool(false)'.
I've tried the to do the same using PDO. The insertion can't be done. So, I tried mysqli prepared statements instead and even this yields the same result. Here is the code.
<?php
$dbh = new mysqli('localhost', 'user', 'pass', 'db');
if(isset($_POST['register'])){
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$passw = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt( $passw );
$stmt = $dbh->prepare("SELECT mail FROM userrecs WHERE mail=?");
$stmt->bind_param('s',$mail);
if($stmt->execute())
{
$stmt->store_result();
$rows = $stmt->num_rows;
if($rows == 1)
{
session_start();
$_SESSION['notification_one'] = 'bla';
header('location:/someplace');
}
else {
$statement = $db->prepare("INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param('ssssiss',$ip,$name,$mail,$encrypted_pass,$codeone,$descs,$newstrings);
try {
if($statement->execute())
{
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
}
else
{
var_dump($statement->execute());
$statement->errorInfo();
}
}
catch(PDOException $pe) {
echo "S";
echo('Connection error, because: ' .$pe->getMessage());
}
}
}
}
else{
header('location:/someplace');
}
?>
EDIT:
This is the PDO-only code. I was mixing PDO and mysqli in the previous code.
<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'user';
$password = 'pass';
$dbh = new PDO($dsn, $user, $password);
if(isset($_POST['regsubmit'])){
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$pass = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt( $passw );
$sql = "SELECT mail FROM userrecs WHERE mail=:mail";
$statement = $dbh->prepare($sql);
$statement->bindValue(':mail',$mail,PDO::PARAM_STR);
if($statement->execute())
{
if($statement->rowCount() == 1)
{
session_start();
$_SESSION['noti_one'] = 'bla';
header('location:/someplace');
}
else {
$sql2 = "INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (:ip,:name,:mail,:encrypted_pass,:codeone,:descs,:newstrings)";
$stmt = $dbh->prepare($sql2);
$stmt->bindParam(':ip',$ip,PDO::PARAM_STR);
$stmt->bindParam(':name',$name,PDO::PARAM_STR);
$stmt->bindValue(':mail',$mail,PDO::PARAM_STR);
$stmt->bindParam(':encrypted_pass',$encrypted_pass,PDO::PARAM_STR);
$stmt->bindParam(':codeone',$codeone,PDO::PARAM_STR);
$stmt->bindParam(':descs',$descs,PDO::PARAM_STR);
$stmt->bindParam(':newstrings',$temstr,PDO::PARAM_STR);
try {
if($stmt->execute())
{
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
}
else
{
var_dump($stmt->execute());
$stmt->errorInfo();
}
}
catch(PDOException $pe) {
echo "S";
echo('Connection error, because: ' .$pe->getMessage());
}
}
}
}
else{
header('location:/someplace');
}
?>
Please ignore variable or table names. I edited some of the names here.
You are mixing PDO and mysqli driver in the same script, this is not possible.
Please use either one but not both.
PDO is the prefferred extension.
EDIT:
In your query:
INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (...)
NAME is a mysql reserved keyword, you escape it by using backticks:
INSERT INTO userrecs (ip,`name`,mail,pass,codeone_one,desc_one,spcstrings) VALUES (...)
EDIT:
Change
var_dump($statement->execute());
$statement->errorInfo();
to
var_dump($statement->errorInfo());
EDIT:
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'user';
$password = 'pass';
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['regsubmit'])) {
try {
$sql = "SELECT mail FROM userrecs WHERE mail=:mail";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':mail', $_POST['mail'], PDO::PARAM_STR);
if ($stmt->execute() && $stmt->rowCount() == 1) {
session_start();
$_SESSION['noti_one'] = 'bla';
header('location:/someplace');
} else {
$sql = "INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (:ip,:name,:mail,:encrypted_pass,:codeone,:descs,:newstrings)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$stmt->bindValue(':name', $_POST['$name'], PDO::PARAM_STR);
$stmt->bindValue(':mail', $_POST['mail'], PDO::PARAM_STR);
$stmt->bindValue(':encrypted_pass', crypt($_POST['passw']), PDO::PARAM_STR);
$stmt->bindValue(':codeone', $_POST['codeone'], PDO::PARAM_STR);
$stmt->bindValue(':descs', $_POST['desc'], PDO::PARAM_STR);
$stmt->bindValue(':newstrings', 'specialstring', PDO::PARAM_STR);
if ($stmt->execute()) {
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
} else {
var_dump($stmt->errorInfo());
}
}
} catch (PDOException $pe) {
echo "S";
echo('Connection error, because: ' . $pe->getMessage());
}
} else {
header('location:/someplace');
}
I believe you have an error in your logic.
Try this code and see what you get ...
<?php
$dbh = new mysqli('localhost', 'user', 'pass', 'db');
if(isset($_POST['register'])) {
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$passw = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt($passw);
$stmt = $dbh->prepare("SELECT mail FROM userrecs WHERE mail=?");
$stmt->bind_param('s', $mail);
$test = $stmt->execute();
if($test) {
$stmt->store_result();
$rows = $stmt->num_rows;
if($rows == 1) {
session_start();
$_SESSION['notification_one'] = 'bla';
header('location:/someplace');
} else {
$statement = $db->prepare("INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param('ssssiss', $ip, $name, $mail, $encrypted_pass, $codeone, $descs, $newstrings);
try {
if($statement->execute()) {
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
} else {
var_dump($statement->execute());
$statement->errorInfo();
}
} catch (PDOException $pe) {
echo "S";
echo('Connection error, because: ' . $pe->getMessage());
}
}
}else{
echo "test is not ok";
var_dump($test);
}
} else {
header('location:/someplace');
}

PHP - Internal 500 error in function

i'm getting 500 internal error in this script for some reason i looked trough the script for like an hour or two cant find the issue in the function, its not an mysql error ether..
function CreateGame($Game, $Pass, $Diff, $CharInfo, $Lad, $Desc, $Realm, $Hash, $timestamp, $Bot = 0)
{
$uno = false;
include "conf.php";
$conn = new mysqli($serverip, $username, $password, $dbname, $Port);
if ($conn->connect_error) {
die("Connection failed: " . encrypt($conn->connect_error);
}
$game = mysqli_escape_string($conn, $Game);
$pass = mysqli_escape_string($conn, $Pass);
$diff = mysqli_escape_string($conn, $Diff);
$hash = mysqli_escape_string($conn, $Hash);
$charInfo = mysqli_escape_string($conn, $CharInfo);
$desc = mysqli_escape_string($conn, $Desc);
$realm = substr($Realm, 0, 1);
$realm = mysqli_escape_string($conn, $Realm);
$bot = mysqli_escape_string($conn, $Bot);
$lad = mysqli_escape_string($conn, $Lad);
$UserResult = $conn->query("SELECT * from user where hash = '$hash'");
if (!$UserResult)
{
echo encrypt("hash not found: ". $hash);
}
while($row = $UserResult->fetch_assoc())
{
if($uno == false)
{
$uno = true;
$BanCheckQuerrt = "SELECT * from hwid where id = '".$row['HWID']."'";
$BanCheckResult = $conn->query($BanCheckQuerrt);
while($BanCheckRow = $BanCheckResult->fetch_assoc())
{
if((int)$BanCheckRow['banned'] === 0)
{
$sql = "INSERT INTO games (Game, Password, Description, Difficulty, Realm, Ladder, BotGame, created, timestamp ) VALUES ('$game', '$pass', '$desc', '$diff', '$realm', 'lad', '$bot', '$timestamp', '$timestamp')";
if ($conn->query($sql) === TRUE) {
$sqli = "INSERT INTO Players (GameID, Name, timestamp) Values ('".mysqli_insert_id($conn)."', '$charInfo', '$timestamp')";
if ($conn->query($sqli) === TRUE) {
$updateUserQuerry = "UPDATE user SET playerID = '" .mysqli_insert_id($conn). "' where hash = '$hash'";
$conn->query($updateUserQuerry);
echo encrypt(mysqli_insert_id($conn));
} else {
echo "Error: " . $sqli . "\n" . encrypt($conn->error);
}
} else {
echo "Error: " . $sql . "\n" . encrypt($conn->error);
}
}
else
echo encrypt("Banned!");
}
}
}
$conn->close();
}
any suggestion that would fix this problem would be acceptably.

Call to a member function execute() on a non-object in

I have the following error, and this is the exact same form processing file I use for registering a user, but I changed it for the appropriate table and columns. While the reg works fine every time.
Here is the code where the error is located:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
Here is the full code:
<?php
$servername = "localhost";
$username = "root";
$password = "Af2vaz93j68";
$dbname = "pdo_ret";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$eventname = $_POST['eventname'];
$about = $_POST['about'];
$website = $_POST['website'];
if($eventname == '') {
$errmsg_arr[] = 'You must enter your Email';
$errflag = true;
}
if($about == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
if($website == '') {
$errmsg_arr[] = 'You must enter First Name';
$errflag = true;
}
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Youre confusing PDO and mysqli. mysqli does not support named parameters so you stmt is not compiling and Mysqli::prepare is returning false. Additionally mysqli does not support passing the param to be bound through mysqli_stmt::execute so even if you switch to positional placeholders your execute will fail.
This is what you would need for mysqli:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
// check to make sure the statement was prepared without error
if ($stmt) {
// the statement is good - proceed
$stmt->bind_param('sss', $eventname, $about, $website);
$stmt->execute();
}
Additionally this makes no sense at all:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will just run the same query again either inserting a second row of the exact same data, or perhaps creating a duplicate key error depending upon your schema.
If you want to test that the previous query succeeded you would do something like:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param('sss', $eventname, $about, $website);
$success = $stmt->execute();
} else {
$success = false;
}
if ($success === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
If you want to use PDO (which i prefer and usually recommend) your code would look something like this:
$conn = PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $sql . "<br>" . $e->getMessage();
}

Uncaught exception 'PDOException' error in my pdo

after running my code i got this kind of error, can anyone help me fix it please. The error starts after putting a code to filter if the email is duplicate or not in the database.
here is the error i got:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$email = #$_POST['email'];
$dupesql = "SELECT * FROM students WHERE email = :email ";
$dupesql = $dbc->prepare($dupesql);
$dupesql->bindParam(':name', $email);
$dupesql->execute();
$num_rows = $dupesql->rowCount();
if($num_rows === 0)
{
echo "1";
$q = "INSERT INTO students(name, age, address, gender, email ) VALUES(:name, :age, :address, :gender, :email)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':email', $email);
$results = $query->execute();
}else{
echo "0";
exit;
}
?>
Well you are facing this error because you are using a wrong parameter in your query.
$dupesql->bindParam(':name', $email);
:name doesn't exists so it should :email.

Categories