How to convert MySQL code into PDO statement? - php

I need to change the first if statement into a PDO statement but I'm not sure how to go about it. Please can someone help?
When users submit a form I want their email address to be pulled from the users table on the database into this page on the website, using the numbered $id they are assigned when they sign up.
$table = 'suggestions';
$id = (isset($_SESSION['u_id']) ? $_SESSION['u_id'] : null);
if ( NULL !== $id) {
$sql = mysqli_query($conn, "SELECT email FROM users WHERE u_id='$id'");
$fetch = mysqli_fetch_assoc($sql);
$email = $fetch['email'];
}
$email;
$optionOne = '';
$optionTwo = '';
$suggestions = selectAll($table);
if (isset($_POST['new-suggestion'])) {
global $conn;
$id;
$email;
$optionOne = $_POST['optionOne'];
$optionTwo = $_POST['optionTwo'];
$sql = "INSERT INTO $table (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
if (!empty($optionOne) && !empty($optionTwo)) {
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $id, $email, $optionOne, $optionTwo);
$stmt->execute();
} else {
echo "All options must be entered";
}
}

Make a connection
Firstly you need to replace your mysqli connection with a PDO one (or at least add the PDO connection alongside the mysqli one!).
// Define database connection parameters
$db_host = "127.0.0.1";
$db_name = "name_of_database";
$db_user = "user_name";
$db_pass = "user_password";
// Create a connection to the MySQL database using PDO
$pdo = new pdo(
"mysql:host={$db_host};dbname={$db_name}",
$db_user,
$db_pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
Updating your code
Prepared statements with mysqli and PDO
It's almost always better to use prepared statements when putting variable data into an SQL query. Not only is it safer (if the data comes from any sort of user generated input) but it also makes it easier to read, and easier to run multiple times with different values.
Prepared query with mysqli:
$sql = "SELECT column1, column2 FROM table WHERE column3 = ? AND column4 = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("si", $string_condition, $int_condition);
$query->execute();
$query->store_result();
$query->bind_result($column1, $column2);
$query->fetch();
echo "Column1: {$column1}<br>";
echo "Column2: {$column2}";
Prepared query with PDO:
$sql = "SELECT column1, column2 FROM table WHERE column3 = ? AND column4 = ?";
$query = $pdo->prepare($sql);
$query->execute([$string_condition, $int_condition]);
$row = $query->fetchObject();
# $row = $query->fetch(); // Alternative to get indexed and/or associative array
echo "Column1: {$row->column1}<br>";
echo "Column2: {$row->column2}";
Updated code
// Using the NULL coalescing operator here is shorter than a ternary
$id = $_SESSION['u_id'] ?? NULL;
if($id) {
$sql = "SELECT email FROM users WHERE u_id = ?";
$query = $pdo->prepare($sql); // Prepare the query
$query->execute([$id]); // Bind the parameter and execute the query
$email = $query->fetchColumn(); // Return the value from the database
}
// Putting "$email" on a line by itself does nothing for your code. The only
// thing it does is generate a "Notice" if it hasn't been defined earlier in
// the code. Best use:
// - The ternary operator: $email = (isset($email)) ? $email : "";
// - The NULL coalescing operator: $email = $email ?? "";
// - OR initialize it earlier in code, before the first `if`, like: $email = "";
// N.B. Instead of "" you could use NULL or FALSE as well. Basically in this case
// anything that equates to BOOL(FALSE); so we can use them in `if` statements
// so the following (2 commented lines and 1 uncommented) are effectively
// interchangeable.
$email = $email ?? "";
# $email = $email ?? FALSE;
# $email = $email ?? NULL;
// Presumably you will also want to change this function to PDO and prepared statements?
// Although it doesn't actually do anything in the code provided?
$suggestions = selectAll($table);
// Same as with email, we're just going to use the NULL coalescing operator.
// Note: in this case you had used the third option from above - I've just
// changed it so there is less bloat.
$optionOne = $_POST['optionOne'] ?? "";
$optionTwo = $_POST['optionTwo'] ?? "";
$newSuggestion = $_POST['new-suggestion'] ?? "";
// There's no point nesting `if` statements like this when there doesn't appear to be any
// additional code executed based on the out come of each statement? Just put it into one.
// We now don't need to use empty etc. because an empty, false, or null string all.
// equate to FALSE.
if($newSuggestion && $id && $email && $optionOne && $optionTwo) {
// Not sure why you've made the the table name a variable UNLESS you have multiple tables
// with exactly the same columns etc. and need to place in different ones at different
// times. Which seems unlikely so I've just put the table name inline.
$sql = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
$query = $pdo->prepare($sql);
$query->execute([$id, $email, $optionOne, $optionTwo]);
}
else{
echo "All options must be entered";
}
Without comments
$id = $_SESSION['u_id'] ?? NULL;
if($id) {
$sql = "SELECT email FROM users WHERE u_id = ?";
$query = $pdo->prepare($sql);
$query->execute([$id]);
$email = $query->fetchColumn();
}
$email = $email ?? "";
$suggestions = selectAll($table);
$optionOne = $_POST['optionOne'] ?? "";
$optionTwo = $_POST['optionTwo'] ?? "";
$newSuggestion = $_POST['new-suggestion'] ?? "";
if($newSuggestion && $id && $email && $optionOne && $optionTwo) {
$sql = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
$query = $pdo->prepare($sql);
$query->execute([$id, $email, $optionOne, $optionTwo]);
}
else{
echo "All options must be entered";
}

Related

Inserting data in diferent tables

Im trying to add data to diferent tables in MySQL, but at the moment of run my code, it shows me a error is it "Fatal error: Uncaught Error: Call to a member function query()", is the firs time that y use the query function so I don't know whats going wrong.
<?php
session_start();
$_SESSION['ID_user'];
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = '$id' LIMIT 1");
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "UPDATE user SET Name_user='$name', password='$password' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->bindParam(':name', $_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $result['name'];
$lastid = $conn->query("SELECT last_insert_id()")->fetch();
$insert = "INSERT INTO rel_company_user (ID_user) VALUES ('$id')";
$in = $conn->prepare($insert);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES ('$company')";
$in = $conn->prepare($insert);
$in->execute();
$update = "UPDATE rel_company_user SET ID_company='$lastid' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
You should use parameters in all your queries. And you can't use bindParam() if you didn't put a placeholder in the query.
FILTER_SANITIZE_SPECIAL_CHARS is not a valid argument to bindParam(). The third argument is an optional data type.
You never set $thelast anywhere, that should be $conn.
If $id is already assigned, you can't use LAST_INSERT_ID() to get ID_user. Just insert that value into the user table.
You don't need to perform a query to get the last insert ID. Just use LAST_INSERT_ID() in the VALUES list of the next INSERT query.
You can't fetch the results of an UPDATE query.
You can't get the last insert ID if you haven't done an insert. The UPDATE user query should be INSERT INTO user.
In several places you assigned the SQL to $insert, but then did $conn->prepare($update).
<?php
session_start();
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = :id LIMIT 1");
$resultset->bindParam(':id', $id);
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "INSERT INTO user (ID_user, Name_user, password) VALUES (:id, :name, :password)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->bindParam(':name', $name);
$up->bindParam(':password', $password);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $name;
$insert = "INSERT INTO rel_company_user (ID_user) VALUES (:id)";
$in = $conn->prepare($insert);
$in->bindParam(':id', $id);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES (:company)";
$in = $conn->prepare($insert);
$in->bindParam(':company', $company);
$in->execute();
$update = "INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), :id)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>

Catchable fatal error: Object of class mysqli_result could not be converted to string on line 12

I'm getting this error for the following php code on line 12. I'm trying to insert data into a table and if it succeeds, redirect to another page after alert.
<?php
session_start();
include 'dbconn.php';
$name = $_POST["name"];
$hof = $_POST["hof"];
$tier = $_POST["tier"];
$services = $_POST["services"];
$proced = $_POST["proced"];
$addr = $_POST["addr"];
$phone = $_POST["phone"];
$depname = $_SESSION['depname'];
$qry = "INSERT INTO '.$depname.'(name,hof,tier,services,method,address,phone) VALUES ('$name','$hof','$tier','$services','$proced','$addr','$phone')"; //This is where the problem is;
if(mysqli_query($conn,$qry) === TRUE) {
echo "<script type='text/javascript'>alert('Success');
window.location='welcome.php';
</script>";
}
else{
echo "<script type='text/javascript'>alert('Error');
window.location='welcome.php';
</script>";
}
?>
In addition to what everyone else said this should fix your errors. You will still have security problems that you need to fix.
Also, I don't use mysqli I use PDO so you will have to forgive me if the syntax is slightly wrong.
Your problem is that mysqli_query() doesn't return a row. You need to need to fetch a row from your result and then assign it to $_SESSION['depname']
Login.php should look like this
// Note we are using prepared statements to prevent SQL injections
// Also note the use of backticks `, which are used for identifiers
$mysqli = new mysqli('host', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT `id`,`depname` FROM `admin` WHERE `username` = ? and password = ?');
$stmt->bind_param('ss', $myusername, $mypassword);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1) {
session_start();
$row = $result->fetch_assoc();
$_SESSION['depname'] = $row['depname'];
header("location: welcome.php");
exit;
}
Other Script
<?php
session_start();
include 'dbconn.php';
$name = $_POST["name"];
$hof = $_POST["hof"];
$tier = $_POST["tier"];
$services = $_POST["services"];
$proced = $_POST["proced"];
$addr = $_POST["addr"];
$phone = $_POST["phone"];
$depname = $_SESSION['depname'];
$qry = "INSERT INTO `{$depname}` (`name`,`hof`,`tier`,`services`,`method`,`address`,`phone`) VALUES (?,?,?,?,?,?,?)";
// prepare our query to prevent sql injections
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('sssssss', $name, $hof, $tier, $services, $proced, $addr, $phone);
$stmt->execute();
// not sure why you aren't using header here like #JayBlanchard said, but whatever
if($stmt->affected_rows == 1) {
echo "<script type='text/javascript'>alert('Success');
window.location='welcome.php';
</script>";
}
else
{
echo "<script type='text/javascript'>alert('Error');
window.location='welcome.php';
</script>";
}

Check if user exists in database

I've made a user class which validates the data passed through the form and then subsequently updates the database table users. I want to add extra functionality such as checking if the username and email exists in the table, I've added a little script however it doesn't seem to be working.
I inserted a duplicated email address and I did not get the error message "email exists" instead I get the success message "1 row inserted":
Am I doing something wrong below? Is there perhaps a better way to approach this?
public function insert() {
if (isset($_POST['submit'])) {
$email = isset($_POST['email']) ? $this->mysqli->real_escape_string($_POST['email']) : '';
$result = $this->mysqli->prepare("SELECT * FROM users WHERE email='".$email."'");
if ($result->num_rows) {
echo "email exisits!";
}
else
{
$stmt = $this->mysqli->prepare("INSERT INTO users (username, password, name, email) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $username, $password, $name, $email); // bind strings to the paramater
//escape the POST data for added protection
$username = isset($_POST['username']) ? $this->mysqli->real_escape_string($_POST['username']) : '';
$cryptedPassword = crypt($_POST['password']);
$password = $this->mysqli->real_escape_string($cryptedPassword);
$name = isset($_POST['name']) ? $this->mysqli->real_escape_string($_POST['name']) : '';
$email = isset($_POST['email']) ? $this->mysqli->real_escape_string($_POST['email']) : '';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
}
You are using the worst API you ever can choose.
With safeMysql it would be
$exists = $this->db->getOne("SELECT 1 FROM users WHERE email=?s", $_POST['email']);
if ($exists) {
echo "email exisits!";
}
With PDO it is slightly longer but usable
$stmt = $this->db->prepare("SELECT 1 FROM users WHERE email=?");
$stmt->execute(array($_POST['email']));
$exists = $stmt->fetchColumn();
if ($exists)
{
echo "email exisits!";
}
But with raw mysqli you will need a screenful of code only to check if user exists.
So, the whole function using safeMysql would be
public function insert()
{
if (!isset($_POST['submit'])) {
return FALSE;
}
$sql = "SELECT 1 FROM users WHERE email=?s";
$exists = $this->db->getOne($sql, $_POST['email']);
if ($exists)
{
echo "email exisits!";
return FALSE;
}
$sql = "INSERT INTO users SET ?u";
$allowed = array('username', 'name', 'email');
$insert = $this->db->filterArray($_POST, $allowed);
$insert['password'] = crypt($_POST['password']);
$this->db->query($sql, $insert);
return $this->db->afectedRows();
}
you need to use this code after prepare statement
$stmt->execute();
$stmt->store_result();
put this
if ($result->num_rows > 0) {
echo "email exisits!";
}
instead of
if ($result->num_rows) {
echo "email exisits!";
}
First, you are using prepare (great!) but then you are just passing in the value of email, effectively defeating the benefit of prepared statements.
Second, you never execute the query, which is why you don't get anything in num_rows.
public function insert() {
$result = $this->mysqli->prepare("SELECT COUNT(*) FROM users WHERE email=?");
$result->bind_param("s", $_POST['email']);
$result->execute();
$result->bind_result($email_count);
if ($email_count) {
echo "email exisits!";
} else {
# your other logic
From what I can see you're not assigning a value to num_rows prior to testing it with if ($result->num_rows), so it will always be 0

Insert NULL instead of empty values using MySQLi

I have a form with some optional fields. In the database those fields are set to accept NULL.
The code below will throw an error if some field is empty. Could you please assist on what is the best way to avoid this? The only solution I was thinking of is to set the vars to ' ' if is empty().
$query = "INSERT INTO gifts (dateRequest, firstName, lastName, note, lastUpdated)
VALUES (?, ?, ?, ?, NOW())";
if ($stmt = $dbc->prepare($query)) {
$dateRequest = $_POST['dateRequest'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$note = $_POST['note'];
$stmt->bind_param('ssss', $dateRequest, $firstName, $lastName, $note);
if ($stmt->execute()) {
$stmt->close();
header('Location: index.php');
} else {
echo $stmt->error;
}
}
I would rather suggest to check $_POST paramenters before definied them so if a variable is not empty set values otherwise set as NULL
if(!empty($_POST['dateRequest'])) { $dateRequest = $_POST['dateRequest']; } else { $dateRequest = NULL; }
if(!empty($_POST['firstName'])) { $firstName = $_POST['firstName']; } else { $firstName = NULL; }
if(!empty($_POST['lastName'])) { $lastName = $_POST['lastName']; } else { $lastName = NULL; }
if(!empty($_POST['lastName'])) { $note = $_POST['note']; } else { $note = NULL; }
This will prevent you to pass empty parameters in your query.
Since PHP 7 you can set the default value for a variable using the elvis-operator.
$dateRequest = $_POST['dateRequest'] ?: null;
$firstName = $_POST['firstName'] ?: null;
$lastName = $_POST['lastName'] ?: null;
$note = $_POST['note'] ?: null;
If any of the fields is empty or undefined it will set the value to NULL and insert that into database instead.
As a side note you should read How to get the error message in MySQLi? instead of print out the error messages manually.

PDO - bindParam not working

I'm creating a PDO class to use on my projects, but since I'm new to it I'm not being able to bind parameters to a prepared sql statement, with not error whatsoever. Here's the function that is ment to do it :
# ::bindParam
public static function bind()
{
# get function arguments
$args = func_get_args();
# check for any arguments passed
if (count($args) < 1)
{
return false;
}
foreach ($args as $params)
{
# named variables for convenience
$parameter = $params[0];
$variable = $params[1];
$data_type = isset($params[2]) ? $params[2] : PDO::PARAM_STR;
$length = isset($params[3]) ? $params[3] : null;
# bind param to query
Database::$statement->bindParam($parameter, $variable, $data_type, $length) or die('error');
}
}
and a prepared sql statement :
SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1
Can someone point me in the right direction? The query produces no errors at this point. Note that I am assuming the problem is here, although it might not, since I'm only using bindParam() and prepare().
edit - trigger code
$email = $_POST['email'];
$password = $_POST['password'];
$password = hash('sha256', $password);
$this->db->prepare('SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1');
$this->db->bind(
array(':email', $email),
array(':password', $password)
);
$status = $this->db->execute();
if ($status)
{
$result = $this->db->fetch('assoc');
$this->template->user = $result;
}
else
{
$this->template->user = false;
}
As #YourCommonSense already mentioned, raw PDO interface is a little bit clearer, however the problem is probably due to the use of function PDOStatement::bindParam() instead of PDOStatement::bindValue().
The difference between those two is that, the first one takes a variable reference, which is constantly overwritten in your foreach loop, while the last one takes the actual value of the variable.
If you're looking for some more friendly database connection interface, why won't you try Doctrine DBAL?
Just get rid of this function, PDO already has it
$email = $_POST['email'];
$password = $_POST['password'];
$password = hash('sha256', $password);
$this->db->prepare('SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1');
$stmt = $this->db->execute(array(':email'=> $email,':password' => $password));
$this->template->user = $this->db->fetch();
That's all code you need (assuming your class' execute is a regular PDO execute)
Or, to make it in raw PDO:
$email = $_POST['email'];
$password = $_POST['password'];
$password = hash('sha256', $password);
$sql = 'SELECT * FROM users WHERE email = ? AND password = ? LIMIT 1';
$stmt = $this->db->prepare($sql);
$stmt->execute(array($email, $password));
$this->template->user = $stmt->fetch();
So, it seems your class require more code than raw PDO. Are you certainly sure you need this class at all?

Categories