Prepared statement didn't execute - php

I have simple web application with back end in PHP. I tried for three hours but couldn't solve the problem.
My code is as follows:
1. db_connect.php
<?php
define("HOST", '127.0.0.1');
define("USER", 'root');
define("PASSWORD", '');
define("DB", 'tourist guide');
$con = new mysqli(HOST,USER,PASSWORD,DB);
if ($con->connect_errno){
die("Database Connection Failed");
exit();
}
2. index.php
<?php
require_once 'db_connect.php';
$response = array();
$result = "";
if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email'])&& isset($_POST['password'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$stmt = $con->prepare("INSERT INTO
user_accounts
(first_name,last_name,email,password)
VALUES
(?,?,?,?)");
echo 'prepared statement executed. ';
$stmt->bind_param('ssss', $firstname, $lastname, $email, $password);
echo 'values given. ';
$result = $stmt->execute();
echo 'statement is executed. ';
$stmt->close();
}
if ($result) {
$response["success"] = 1;
$response["message"] = "account successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "An error occurred during registration.";
echo json_encode($response);
}
?>
And the output is as follows:
prepared statement executed. values given. statement is executed. {"success":0,"message":"An error occurred during registration."}
Only the mistake must be $result = $stmt->execute();. Am I wrong here? or the error is something else? plz help.
UPDATE:
From fred's comment I added:
if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);}
Now he real error is showing:
Cannot add or update a child row: a foreign key constraint fails
looks like the error is in my database foreign keys...I'll solve it later..If you know about the error right now, then please say me...thanks fred.

As per OP's wish to close the question, seeing that the error has been found.
It seems like you're closing your DB connection too soon.
Place $stmt->close(); before your closing ?> tag.
Also, instead of the whole if/else block including $result = $stmt->execute(); replace it with if(!$stmt->execute()){trigger_error("There was an error....".$con->error, E_USER_WARNING);} in order to see the real error why it's failing.
You should also replace die("Database Connection Failed"); with
die('Connection failed [' . $con->connect_error . ']');
to get the real error in case your connection should ever fail.
Seeing that the problem is with your foreign keys.

Related

Unable to method chaining in MySQLi prepared statement using PHP

I am a beginner to PHP. I tried not to put $conn->prepare($sql_stmt) in one variable and just applied method chaining. But I got "Error while executing".
<?php
include_once 'dbh.inc.php';
if(isset($_POST['submit_btn']))
{
$fullname = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$sql_stmt = "INSERT INTO signup (name, username, passwrd) VALUES (?,?,?);";
//prepare and bind
$conn->prepare($sql_stmt)->bind_param("sss", $fullname, $username, $password);
//execute
if($conn->prepare($sql_stmt)->execute())
{
echo "User created";
}
else
{
echo "Error while executing";
}
}
else
{
echo "Unable to sign up.";
}
However if I instantiate $sql = $conn->prepare($sql_stmt) like below
<?php
include_once 'dbh.inc.php';
if(isset($_POST['submit_btn']))
{
$fullname = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$sql_stmt = "INSERT INTO signup (name, username, passwrd) VALUES (?,?,?);";
//prepare and bind
$sql = $conn->prepare($sql_stmt);
$sql->bind_param("sss", $fullname, $username, $password);
//execute
if($sql->execute())
{
echo "User created";
}
else
{
echo "Error while executing";
}
}
else
{
echo "Unable to sign up.";
}
It works and returns "User created". Why is that so?
Method chaining is not possible with mysqli. The return value of bind_param() is a boolean. It does not return self. You must call the methods like you showed in the second example:
$sql = $conn->prepare($sql_stmt);
$sql->bind_param("sss", $fullname, $username, $password);
$sql->execute();
In fact, mysqli is not very suitable to be used on its own in your application. If you want something simpler, then use PDO. If for some strange reason you must use mysqli, then you require some kind of abstraction layer that will prevent you from dealing with mysqli functions directly.
As of PHP 8.1, you can pass parameters directly in mysqli_stmt::execute(), which enables you to do method chaining in one line:
$sql = $conn->prepare($sql_stmt)->execute([$fullname, $username, $password]);
Also, please stop checking the return value of execute. You should enable mysqli error reporting instead. How to get the error message in MySQLi?

Doesn't insert data in DB

Almost 2 days my computer doesn't want to insert data in my DB, tried to change a lot in code but still not works. (and deleted ` - and nothing changed). Could you suggest what is the reazon?
<?php
include '../db.php';
try {
$stmt = $dbh->prepare(" INSERT INTO `users` (`login`,`password`) VALUES (:login, :password) ");
$stmt->bindParam(':login', $login );
$stmt->bindParam(':password', $password );
$_POST['login'] = $login;
$_POST['password'] = $password;
$stmt->execute();
}
catch (exeption $e) { // Если ошибка - показать сообщение об ошибке
echo $e->getMessage();
}
echo "\nPDO::errorCode(): ", $dbh->errorCode();
echo " ";
$rows = $stmt->fetchAll();
$num_rows = count($rows);
echo $num_rows;
/*header("location:../auth.php");*/
?>
Returns PDO::errorCode(): 00000 (thats fine), but it returns 0 rows! Maybe that's the reason
And my db.php file:
<?php
try { //Connecting to db via login and password
$user = 'mydatabases';
$pass = '1234';
$dbh = new PDO('mysql:host=localhost;dbname=dbname', $user, $pass);
}
catch (exeption $e) { //if any mistakes show message of error
echo $e->getMessage();
}
?>
In my DB was 2 extra columns I wanted them to be empty (they didnt fill when user register), that was the reason why code didnt work and didnt send me any error messages

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

How to write REST web service in PHP for Android application backend?

Currently, I am developing an Android application with involves client server architecture. It is said to me that I have to write REST web service in PHP for back end communication. At that time I didn't know about RESTful architecture and etc..
In last 3 days, I learned much about REST web services and tried many tutorials. Then, I tried some code from tutorials and from SO. What I have tried so far is as follows:
I have three php files, a database named xyz and table named user_accounts with basic user details in phpmyadmin. And I have installed Advanced REST client on my browser. All code is in WWW directory of WAMP server under folder named my project. So, let me show some code:
1. db_connect.php
<?php
define("SERVER", '127.0.0.1');
define("USER", 'root');
define("PASSWORD", '');
define("DB", 'xyz');
$con = new mysqli(SERVER,USER,PASSWORD,DB);
if ($con->connect_errno){
die("Database Connection Failed");
exit();
}
In second file I have a function named adduser for adding user records into the database :
index.php :
<?php
require_once('db_connect.php');
$response = array();
$result = "";
function adduser($firstname, $lastname, $email, $password) {
global $app;
$req = $app->request();
$firstname= $req->params['firstname'];
$lastname= $req->params['lastname'];
$email = $req->params['email'];
$password = $req->params['password'];
$stmt = $con->prepare("INSERT INTO user_accounts (first_name,last_name,email,password)VALUES (?,?,?,?)");
$stmt->bind_param('ssss', $firstname, $lastname, $email, $password);
$stmt->execute();
$result = $stmt->close();
}
if($result){
$response["success"] = 1;
$response["message"] = "account successfully created.";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "An error occurred during registration.";
echo json_encode($response);
}
?>
When I test it using advanced REST client by giving url :
http://127.0.0.1/my project/index.php/adduser
and method POST and parameters:
firstname=somename&lastname=name&email=a#b.gmail.com&password=101010
It shows following response:
{"success":0,"message":"An error occurred during registration."}
I can not identify where the error is. I am new to this. Please help if anything wrong.
your should try this:
$affected_rows = $stmt->rowCount();
Update:
then check if row count is greater than 0.
<?php
require_once('db_connect.php');
$response = array();
$result = "";
function adduser($firstname, $lastname, $email, $password) {
global $app;
$req = $app->request();
$firstname= $req->params['firstname'];
$lastname= $req->params['lastname'];
$email = $req->params['email'];
$password = $req->params['password'];
$stmt = $con->prepare("INSERT INTO user_accounts (first_name,last_name,email,password)VALUES (?,?,?,?)");
$stmt->bind_param('ssss', $firstname, $lastname, $email, $password);
$stmt->execute();
return $stmt->rowCount();
}
$adduser = addUser($firstname, $lastname, $email, $password);
if($adduser > 0){
$response["success"] = 1;
$response["message"] = "account successfully created.";
echo json_encode($response);
} else{
$response["success"] = 0;
$response["message"] = "An error occurred during registration.";
echo json_encode($response);
}

Error that will not show itself

I'm trying to code a registration system for a system I am making. Currently, I am receiving a MySQL error that makes me want to tear my head out each and every time I see it.
function UserRegister($user,$pass,$email,$first,$last)
{
$sqlfirst = mysql_real_escape_string($first);
$sqllast = mysql_real_escape_string($last);
$sqluser = mysql_real_escape_string($user);
$hashpass = crypt($pass);
$sqlpass = mysql_real_escape_string($hashpass);
$sqlemail = mysql_real_escape_string($email);
$sql = "SELECT *
FROM planerentalusers
WHERE user = '$sqluser' ";
if($result = mysqli_query($GLOBALS['db'],$sql))
{
$rowcount=mysqli_num_rows($result);
if($rowcount == 1)
{
echo "ERROR: There is already an account with that username! Click <a href='/PHPCalTest/login.php>here </a>to login if this is you. Otherwise, go back and try a different username.";
}
else
{
$sql2 = "INSERT INTO planerentalusers (first,last,user,pass,email) VALUES ('$sqlfirst','$sqllast','$sqluser','$sqlpass','$sqlemail')";
$result2 = mysqli_query($GLOBALS['db'],$sql);
if($result2 == true)
{
return true;
}
else return false;
}
}
else return false;
mysqli_free_result($result);
}
Above is the function that throws the error.
there is no PHP stack trace that is being thrown, so here is what I pinpointed it to: the query is failing. But how, I do not understand. Perhaps someone can point me in the right direction.
That is not a direct answer to your question. It has been solved somewhere between the comment lines.
Now, you can streamline and secure your code if you will:
use prepared statements. It's only natural since you are already using mysqli_* extension. Parameters that you pass to the prepared INSERT statement will be properly escaped.
utilize INSERT IGNORE syntax and check for affected rows with affected_rows. That way you do all you need to do hitting your database only once.
For INSERT IGNORE to work properly you have to have a UNIQUE constraint on username column.
ALTER TABLE planerentalusers ADD UNIQUE (username);
Now if you issue an INSERT IGNORE statement and a username doesn't exist a row will be inserted and affected_rows will return 1. If a username already exists then IGNORE clause will allow your INSERT statement to complete without throwing an error and affected_rows will return 0.
That being said an improved version of your function might look like
function UserRegister($db, $username, $pass, $email, $first, $last) {
$sql = "INSERT IGNORE INTO planerentalusers (first, last, username, pass, email) VALUES (?, ?, ?, ?, ?)";
// prepare the statement
$stmt = $db->prepare($sql);
if (!$stmt) {
die('Can\'t prepare: ' . $db->error); //TODO better error handling
}
// bind parameters
$stmt->bind_param('sssss', $first, $last, $username, $pass, $email);
if (!$stmt) {
die('Can\'t bind parameters: ' . $db->error); //TODO better error handling
}
// execute
$stmt->execute();
if (!$stmt) {
die('Query execution failed: ' . $db->error); //TODO better error handling
}
// get the number of affected rows
$affected_rows = $stmt->affected_rows;
// close the statement
$stmt->close();
return $affected_rows;
}
and the calling code
$first = $_POST['first'];
$last = $_POST['last'];
$username = $_POST['username'];
$pass = crypt($_POST['pass']);
$email = $_POST['email'];
//create a connection to the database
$db = new mysqli('localhost', 'user', 'password', 'dbname');
if ($db->connect_errno) {
die('Connection failed: ' . $db->connect_error); //TODO better error handling
}
if (!UserRegister($db, $username, $pass, $email, $first, $last)) {
echo "ERROR: There is already an account with that username! Click <a href='/PHPCalTest/login.php'>here </a>to login if this is you. Otherwise, go back and try a different username.";
} else {
echo "Account successfully created";
}
Note that
A reference to an open db connection is explicitly passed to the function instead of using $_GLOBALS['db']
presentation logic (echoing an error message and a link) is moved out to the calling code
Basic error handling is implemented throughout the function

Categories