How to tell which query had an error? [duplicate] - php

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I am trying to convert my mysqli database that was very vulnerable to PDO prepared statements. I think i almost got it since it actully inputs the registration data to the database but not to the other databases. So i think there must be some issues on those queries but i can't figure it out. Here below is my code.
<?php
session_start();
// DATABASE CONNECTION
$user = '****';
$pass = '****';
//CREATE CONNECTION
// $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$pdo = new PDO('mysql:host=localhost;dbname=****', $user, $pass);
// ASSIGN VARIABLE FROM FORM
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$password = password_hash($password, PASSWORD_BCRYPT);
// CHECK IF USER IS UNIQUE
$stmt = $pdo->prepare("SELECT username FROM users WHERE username = :name");
$stmt->bindParam(':name', $username);
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo "That username already exist!";
} else {
//INSERT DATA INTO DATABASE
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql2 = "INSERT INTO progression (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql3 = "INSERT INTO powervalues (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$query2 = $pdo->prepare($sql2);
$query3 = $pdo->prepare($sql3);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
$result1 = $query1->execute(array( ':username'=>$username ));
$result2 = $query2->execute(array( ':username'=>$username ));
$result3 = $query3->execute(array( ':username'=>$username ));
//EXECUTE QUERY
if ($result && $result1 && $result2 && $result3) {
$_SESSION['Accountsucess'] = "Account has been added sucessfully.";
header("location: ../../index.php?page=index");
} else {
echo "Error database failure";
}
}

Instead of continually selecting various parts of information, once you have inserted the user in the users table, fetch the last insert ID and then use that in subsequent calls...
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES (:id,:username)";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
// Fetch id of new user
$id = $pdo->lastInsertId();
$result1 = $query1->execute(array( ':id' => $id, ':username'=>$username ));
Repeat this same logic for each of the other statements.

Related

PHP Prepared statements inserting data into all but one table (MySQL)

I'm working on an inbox system. On the front end, it uses jQuery and Ajax so the page doesn't refresh. I've got that part handled. On the back end, there are 3 tables (for now) that get data inserted.
Here is a basic rundown of the relation structures:
conversations:
conversation_id int(11) primary key
conversation_subject varchar(128)
conversations_members:
conversation_id int(11)
user_id int(11)
conversation_last_view int(10)
conversation_deleted int(1)
conversations_messages:
message_id int(11) primary key
conversation_id int(11)
user_id int(11)
message_date timestamp
message_text text
There is an additional problem since the sender_id is always 0, but that will have to be for another question since it's off topic.
The problem lies in the conversations_members table. Everything else gets entered into the conversations and conversations_messages tables. Here is the PHP. The issue is the very last SQL query at the bottom:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('../inc/connect.php');
if (!isset($_SESSION['username'])) {
session_start();
}
$recipient_username = "";
$sender_id = "";
$a = 0;
$b = 0;
if(isset($_POST['subject'], $_POST['msg_body']) && !empty($_POST['subject']) && !empty($_POST['msg_body'])) {
//get ID of sender
$sender_id_query = "SELECT id FROM `users` WHERE username = ?";
$stmt = $connection->prepare($sender_id_query);
$stmt->bind_param('s', $_SESSION['username']);
$stmt->execute();
$result = mysqli_query($connection, $sender_id_query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
//$row['id'] = $sender_id; //neither of these work
$sender_id = $connection->insert_id; //Always zero
}
}
$stmt->close();
//get username of recipient
$recipient_name_query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $recipient_name_query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$row['username'] = $recipient_username;
}
}
//define post variables
$msg_subject = $_POST['subject'];
$msg_body = $_POST['msg_body'];
$subject = $connection->real_escape_string(htmlentities($msg_subject));
$body = $connection->real_escape_string(htmlentities($msg_body));
$conversation_id = mysqli_insert_id($connection);
//GET RECIPIENT ID
$sql = "SELECT id FROM `users` WHERE username=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('s', $recipient_username);
$result = mysqli_query($connection, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$recipient_id = $row['id'];
}
}
$stmt->close();
//INSERT SUBJECT INTO CONVERSATIONS TABLE
$stmt = $connection->prepare("INSERT INTO `conversations` (conversation_subject) VALUES(?)");
$stmt->bind_param('s', $subject);
$stmt->execute();
$stmt->close();
//INSERT THE IDs AND TIMESTAMPS INTO MESSAGES TABLE
$stmt = $connection->prepare("INSERT INTO `conversations_messages` (conversation_id, user_id, message_date, message_text)
VALUES(?, ?, NOW(), ?)");
$stmt->bind_param('iis', $conversation_id, $sender_id, $body);
$stmt->execute();
$stmt->close();
/*
THE FOLLOWING DATA DOES NOT GET INSERTED.....
*/
//INSERT IDs, LAST_VIEWED, AND DELETED INTO MEMBERS TABLE
$stmt = $connection->prepare("INSERT INTO `conversations_members` (conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('iiii', $conversation_id, $recipient_id, $a, $b);
$stmt->execute();
$stmt->close();
}
I get no errors, and I'm not seeing any typos. Where did I go wrong?
Thanks to the suggestion of additional error checking, it led me to discover what was happening. I completely removed the while loops, and gave each $stmt variable it's own name since I discovered another error after removing the while loops. Every statement after the first was returning a FALSE value since the previous statement wasn't closed. This code works. I get no errors, and it inserts everything into the database as required.
$recipient_username = $_GET['username'];
$username = $_SESSION['username'];
$a = 0;
$b = 0;
//get ID of sender
$sender_id_query = "SELECT id FROM `users` WHERE username = ?";
$stmt = $connection->prepare($sender_id_query);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($sender_id);
$val = $stmt->fetch()[$sender_id];
$stmt->close();
//define post variables
$msg_subject = $_POST['subject'];
$msg_body = $_POST['msg_body'];
$subject = $connection->real_escape_string(htmlentities($msg_subject));
$body = $connection->real_escape_string(htmlentities($msg_body));
$conversation_id = mysqli_insert_id($connection);
//GET RECIPIENT ID
$recipient_id_query = "SELECT id FROM `users` WHERE username=?";
$stmt2 = $connection->prepare($recipient_id_query);
$stmt2->bind_param('s', $recipient_username);
$stmt2->execute();
$stmt2->bind_result($recipient_id);
$val_2 = $stmt2->fetch()[$recipient_id];
$stmt2->close();
//INSERT SUBJECT INTO CONVERSATIONS TABLE
$stmt3 = $connection->prepare("INSERT INTO `conversations` (conversation_subject) VALUES(?)");
$stmt3->bind_param('s', $subject);
$stmt3->execute();
$stmt3->close();
//INSERT THE IDs AND TIMESTAMPS INTO MESSAGES TABLE
$stmt4 = $connection->prepare("INSERT INTO `conversations_messages` (conversation_id, user_id, message_date, message_text)
VALUES(?, ?, NOW(), ?)");
$stmt4->bind_param('iis', $conversation_id, $sender_id, $body);
$stmt4->execute();
$stmt4->close();
//INSERT IDs, LAST_VIEWED, AND DELETED INTO MEMBERS TABLE
$stmt5 = $connection->prepare("INSERT INTO `conversations_members` (conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (?, ?, ?, ?)");
$q = $stmt5->bind_param('iiii', $conversation_id, $recipient_id, $a, $b);
$stmt5->execute();
$stmt5->close();

PHP/MySQL: After inserting the value into a table the value of the variable gets lost and cannot print it out at the end of the file? [duplicate]

This question already has answers here:
Insert_id is null when used directly in next prepared statement
(2 answers)
Closed last year.
I want to do more than one database queries in the same file:
Create a user, select the UID of that newly created user, and assign to that same user a specific role.
After I get the UID from the newly created user I save that value into the $userID variable, but at the end of the file, the variable value gets lost.
Why? (PS: I'm not taking into account security at the moment).
//Create User
$email = strip_tags($_POST['email']);
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$query = "INSERT INTO usuarios
(userEmail)
VALUES
('$email')";
$insertarBase = mysqli_query($conectar,$query);
mysqli_close($conectar);
//look for the UID of the newly created user
$conectar2 = mysqli_connect(HOST, USER, PASS, DATABASE);
$buscarUsuario = "SELECT userID, userEmail
FROM usuarios
WHERE userEmail='$email'
";
$resultadoBusqueda = mysqli_query($conectar2,$buscarUsuario);
$row = mysqli_fetch_array($resultadoBusqueda);
$userID = $row['userID'];
mysqli_close($conectar2);
//assign a role to the newly created user
$conectar3 = mysqli_connect(HOST, USER, PASS, DATABASE);
$asignarRol = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
('$userID', 'registered')
";
$asignarRolenBase = mysqli_query($conectar3,$asignarRol);
mysqli_close($conectar3);
echo $userID; //Here the content of $userID is gone, nothing gets printed out
Edited:
For some weird reason, $userID = mysqli_insert_id($conectar); returns zero.
The creation of the usuarios table statement is this:
CREATE TABLE usuarios(
userID int unsigned not null auto_increment primary key,
userEmail char(50) not null);
Also, echo $asignarRol; returns:
INSERT INTO rolesUsuarios (userID, nombreRol) VALUES ('0', 'noAutorizado')
i tried to tidy up your code and delete superfluous code.
//Create User
$email = $_POST['email']; // you have to verify if this is an email or html etc.
$conectar = new mysqli(HOST, USER, PASS, DATABASE);
$query = "INSERT INTO usuarios
(userEmail)
VALUES
(?)";
$stmt = $conectar->prepare($query);
$stmt->bind_param('s',$email);
$stmt->execute();
$userID = $stmt->insert_id;
$stmt->close();//close statement
//assign a role to the newly created user
$query = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
(?, 'registered')";
$stmt = $conectar->prepare($query);
$stmt->bind_param('i',$userID);
$stmt->execute();
$stmt->close();
$conectar->close();
echo $userID; //Here the content of $userID
First of all , you don't have to create a new db-connection for each statement.
Second: please prepare your statements - for security purposes.
If $userID is empty, make an error_log($userID); after you $userID gets it value, if it's empty , there might be something else wrong.
First as other said to you use prepared statement for SQL injection and second the SQL connection not need to repeat so many time. Too many code and select not need please check the follow.
<?php
$conn = new mysqli(HOST, USER, PASS, DBNAME);
$insert_usuarios = $conn->prepare(" INSERT INTO usuarios ( userEmail ) VALUES ( ? ) ");
$insert_usuarios->bind_param( "s", $userEmail);
$insert_rolesUsuarios = $conn->prepare(" INSERT INTO rolesUsuarios ( userID, nombreRol ) VALUES ( ?, ? ) ");
$insert_rolesUsuarios->bind_param( "is", $userID, $nombreRol);
if(isset($_POST['email'])) {
$userEmail = $_POST['email'];
if (!$insert_usuarios->execute()) { // ERROR
echo('Error'); // OR ACTION THAT YOU LIKE
} else { // SUCCESS
$userID = $insert_usuarios->insert_id; // LAST ID INSERT
$nombreRol = 'REGISTERED';
if (!$insert_rolesUsuarios->execute()) { // ERROR
echo('Error'); // OR ACTION THAT YOU LIKE
} else { // SUCCESS
echo('Done!');
}
}
}
?>
Cheers!!!
Yet another cleanup of your code, following your code style and convention =)
//Create User
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$email = strip_tags($_POST['email']);
$query = 'INSERT INTO usuarios (userEmail) VALUES (?)';
$stmt = mysqli_prepare($conectar, $query);
mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt); //execute query
$userID = mysqli_insert_id($conectar);
//assign a role to the newly created user
$query = "INSERT INTO rolesUsuarios (userID, nombreRol) VALUES (?, 'registered')";
$stmt = mysqli_prepare($conectar, $query);
mysqli_stmt_bind_param($stmt, 's', $userID);
mysqli_stmt_execute($stmt); //execute query
var_dump($userID);
tell me, what did you will get in the end?

Can't insert data into mysql with php

ok so I can connect and view the database with my php code, however I can not insert data into it.here is the query I tested with phpmyadmin which was able insert new data into my table
INSERT INTO `members` ( `id` , `username` , `email` )
VALUES ( 123456789, 'russi', 'baka#dog.com' )
then I tried to put it into my actual php file
<?php
$servername = "localhost";
$username = "root";
$password = "blablabla";
$dbname = "test_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - username: " . $row["username"]. " -email:" . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
so select function works but insert does not.
You are overriding your $sql variable w/o executing it. Besides that you should not use single quotes for columns, but backticks (see When to use single quotes, double quotes, and backticks in MySQL)
Change
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
to
$sql = "INSERT INTO `members` (`id`, `username`, `email`)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$result = $conn->query($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
Change your insert to:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
And call your query:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
//Here, you never execute your query
$result = $conn->query($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
Of course it did not work !
You never execute your INSERT...
<?php
...
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$conn->exec($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
...
:)
remove the single quotes around your column and table names:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
single quotes are only used for char fields.
Also you never execute the insert Statement because you overwrite it.
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
//missing the grave accent
$sql = "INSERT INTO `members` (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT `id`, `username`, `email` FROM `members`";
/* This is the corrrected code */

mysqli_num_rows not working in MySQLi with PHP

I would like to check if there already exists a record before inserting a new one. But it doesn't work so far, here is the script:
<?php
session_start();
$uname = $_SESSION['username'];
$friend = $_GET["newfriend"];
$db = new mysqli("localhost", "...", "....", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
$checkexist = $db->query("SELECT * FROM friends WHERE (username_own='$uname', username='$friend')");
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0) {
//run the query to insert the row
$stmt->execute();
}
Try something like this:
<?php
/* Check if user exists */
$query = "SELECT count(1) FROM friends WHERE username_own=? AND username=?";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->bind_result($count_rows);
$stmt->fetch();
$stmt->close();
}else die("Failed to prepare");
/* If user doesn't exists, insert */
if($count_row == 0){
$query = "INSERT INTO friends (`username_own`, `username`) VALUES (?,?)";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->close();
}else die("Failed to prepare!");
}
Try this:
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0 || $checkexist->mysqli_num_rows <> 0) {
//run the query to insert the row
$stmt->execute();
}
$checkexist->mysqli_num_rows is wrong. It's just
$checkexist->num_rows
or you can use
mysqli_num_rows($checkexist)
Hope this helps.
Replace most of your code with a simple INSERT IGNORE ... or INSERT ... ON DUPLICATE KEY UPDATE ....
The latter lets you change columns if the record already exists (based on any PRIMARY or UNIQUE key(s)).

SQL Selecting Data with WHERE ". $variable ."

my question is:
I have an issue with my code (SELECTING data from MySql)
This is my code
<?php
$user_name = $_SESSION['user_name'];
$user_email = $_SESSION['user_email'];
echo $user_email;
$con = mysqli_connect("localhost", "root", "", "minehelp");
$id_query = mysqli_query($con, "SELECT user_name FROM users_en WHERE user_name = '" . $user_name . "' OR user_email = '" . $user_email . "';");
while ($row_id_query = mysqli_fetch_assoc($id_query)){
print($row_id_query['user_name']);
}
?>
I want to select data WHERE the "user_name is $user_name"
This is login system, that means the $_SESSION'user_name'
is part of my code and i can't remake it.
Thanks for every answer,
Jakubk-0
Should be looking similar to
$sql = "INSERT INTO users (NickName, PassWord, Email)
VALUES (:nick, :pass, :mail)";
$conn->prepare($sql);
$conn->execute(array(':nick' => $NickNaming, ':pass' => $PassWording, ':mail' => $Emailing));
You should use PDO::prepare
Prepares an SQL statement to be executed by the
PDOStatement::execute() method.
and PDO::execute
Execute the prepared statement.
So your prepare and execute would look like this:
$sth = $conn->prepare( 'INSERT INTO users (NickName, PassWord, Email)
VALUES (:nick, :pass, :mail)');
$sth->execute( array(':nick' => $NickNaming,
':pass' => $PassWording,
':mail' => $Emailing));
I tried to not use PDO :
$insert = mysqli_query($con,"INSERT INTO users (Nickname, PassWord, Email)
VALUES ('$NickName','$PassWording','$Emailing')");
That will work

Categories