This question already has answers here:
How to execute two mysql queries as one in PHP/MYSQL?
(8 answers)
Closed 4 years ago.
My question is regarding performance and script optimization. I'm fairly new to PHP and I have something like the following:
$Connection = new mysqli($Server, $DBUsername, $DBPassword, $DBName);
$Connection->query("UPDATE Basket SET Apples='$Apples', Oranges='$Oranges', Bananas='$Bananas' WHERE BasketName='$BasketName'");
$Connection->query("UPDATE Bag SET Napkins='$Napkins' WHERE BagName='$BagName'");
$Connection->query("UPDATE Drinks SET Water='$Water' WHERE DrinksName='$DrinksName'");
Is it ok that I have multiple $Connection->query, one for each table or is there a better way that's faster to write this?
First of all, your code is vulnerable to a SQL injection. You should switch to prepared statements asap.
Using mysqli_real_escape_string is not enough to prevent SQL injections. See Is “mysqli_real_escape_string” enough to avoid SQL injection or other SQL attacks?
An example of a prepared statement:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
To answer your original question. You could use mysqli::multi_query. I personally find it a lot cleaner if the queries are split up query per query.
Related
I have a site where I needed to use separate table names for each of my clients because the data has to be updated all the time with a manual import.
example:
kansas_users
newyork_users
I have set a global variable as $client which will create the state name on all pages so if I echo "$client"; then I will see "kansas" for example on any page.
I would like to include this variable as part of my SQL query if possible to make it easier to code:
SELECT "nick, firstname, lastname, cell
FROM database.$client_members
where active =1 and id = $user->id";
Is this possible or even safe to do?
Yes it possible you can do some thing like below
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = 'kansas';
$table_name = "database." . $conn->real_escape_string($client) . "_members";
$query = sprintf("SELECT nick, firstname, lastname, cell
FROM %s WHERE active = 1 and id = ?", $table_name);
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user->id);
But i think you should seriously consider normalizing your database to avoid such issues
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 4 years ago.
I was wondering Is this code safe form SQL injection and other types of exploits? If it is safe can anyone explain it to me how? And if isn't can anyone make corrections
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form";
//Requesting values form form.html
$a = $_REQUEST['fname'];
$b = $_REQUEST['lname'];
$c = $_REQUEST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " .$conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare ("INSERT INTO my_db (fname, lname, email)
VALUES (?, ?, ?)");
$stmt->bind_param("sss",$a,$b,$c);
$stmt->execute();
echo "new record created successfully";
$stmt->close();
$conn->close();
?>
Yes, it's safe from SQL Injection, but it can be still improved security wise.
SQL Injection is when you concatenate sql query with user parameters, this gives malicious user a chance to inject data or perform dangerous actions in your database.
Assuming you have a code:
$query = 'select * from user where id = ' + $_GET['id'];
Now assume a hacker send the id param as 1 or 1 = 1, so your query becomes
select * from user where id = 1 or 1 = 1
This will return all users.There are also other ways to inject
Since you are using prepared statement and bind all parameters, it's not possible to concatenate sql query.
Security wise,
your code accept $_REQUEST, this includes both GET and POST. This is not a good practice. You should restrict CRUD to POST only.
You are using root (even in develop environment, you shouldn't use root)
I'm totally PHP beginner, and I'm trying to insert variables in a database in PHP and MySQL.
This is my code:
$link = mysql_connect('localhost','','','onlynews') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
$strSQL = "INSERT INTO news(id, title,photo,url,source, at) VALUES('$x','$title','$url','$imgurl ','$source','$at')";
mysql_query($strSQL) or die(mysql_error());
The problem is it is doing: NOTHING! No Entries at all, Nothing changes in the database.
-How can I fix this?
-Do I have to write codes to prevent SQL Injection, even if the variables are coming from an API, not from users?
You have to execute your query using $conn->query($sql);.
However, to avoid SQL injections you should definitely use prepared statements or at least $conn->real_escape_string() to escape the values in your SQL statement.
For example, this is your code using prepared statements:
$servername = "localhost";
$username = "";
$password = "";
$dbname = "onlynews";
$tableName = "news";
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO news (id, title, photo, url, source, at)
VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $thetitle, $urlToImage, $theurl, $thesource, $thetime);
$stmt->execute();
$stmt->close();
You should also add some error checking, since $conn->prepare() and $stmt->execute() may fail (and return false). Of course, establishing the connection to the database during the construction of $conn could also fail, which can be checked using $conn->connect_error.
Trying to just set up something to verify that username = password via num_rows = 1.
Trying to use prepared statements, that I have never used before and i'm missing something. Where does the var in bind_results('s',$variable) come from??
Also, its just not working for me.
<?php
require ($_SERVER['DOCUMENT_ROOT'].'/db-connect.php');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_POST['username'];
//$user = $mysqli->real_escape_string($user);//
$password = $_POST['password'];
//$password = $mysqli->real_escape_string($password);//
if ($stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?")) {
$stmt->bind_result('ss', $username);
$stmt->execute();
$result = $stmt->num_rows;
echo $result;
$stmt->close();
}
$mysqli->close();
?>
I see three problems with this:
$stmt->bind_result('ss', $username);
First, bind_result PHP documentation:
"Binds columns in the result set to variables."
I think you're looking for bind_param. PHP documentation:
"Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare()."
Second, your statement has two parameter markers (?), your bind statement indicates two strings (ss), but you provide only one variable ($username).
Third, $username is not what you're getting from $_POST['username']. You've assigned that to $user. $username is for your database connection.
I think it should work for you with this line instead:
$stmt->bind_param('ss', $user, $password);
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards