Execute SQL Query with PHP - php

I am new to using PHP to run SQL commands but what I'm trying to do is truncate specific tables within my database when the script is run. I can do this fine truncating just one table but when I attempt multiple table I run into issues! Code is below, any pointers?! Thanks in advance
<?php
var_dump($_POST);
$myServer = $_POST['host'];
$myUser = $_POST['user'];
$myPass = $_POST['password'];
$myDB = $_POST['db'];
$con = mysqli_connect($myServer, $myUser, $myPass) or die("Connection
Failed");
mysqli_select_db($con, $myDB)or die("Connection Failed");
$query = ("
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table customers;
TRUNCATE table customers2;
SET FOREIGN_KEY_CHECKS = 1;
");
if(mysqli_query($con, $query)){
echo "table empty";}
else{
echo("Error description: " . mysqli_error($con));}
?>

execute one query at a time
mysqli_query($con, "SET FOREIGN_KEY_CHECKS = 0;");
mysqli_query($con, "TRUNCATE table customers;");
mysqli_query($con, "TRUNCATE table customers2;");
mysqli_query($con, "SET FOREIGN_KEY_CHECKS = 1;");
or use mysqli_multi_query
mysqli_multi_query($con, "
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table customers;
TRUNCATE table customers2;
SET FOREIGN_KEY_CHECKS = 1;
");

mysqli_query only allows one query at a time. If you want to use multiple queries at once, use mysqli_multi_query. Documentation: http://php.net/manual/en/mysqli.multi-query.php
In your code, you would change
mysqli_query($con, $query)
to
mysqli_multi_query($con, $query)

Related

php Update sql and Query

I want to do a query in php, output the data on the page and then modify it in the database.
How do I do that?
Currently I do it like this but it dose not work:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM pics WHERE id = '$id'";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
$dir = $row["dir"];
$likes = $row["likes"];
}
$sqlq = "UPDATE pics SET likes='$likes+1' WHERE id='$id'";
$conn->query($sqlq);
$conn->close();
But the like dose not add to the database.
If you echo your $sqlq out using
echo $sqlq;
you'll see that the '$likes+1' isn't doing what you expect.
You could really simplify it by doing
$sqlq = "UPDATE pics SET likes=likes+1 WHERE id='$id'";
which removes any risk of two users updating the database at teh same time overwriting each other.
But you should really check out using "parameterized queries" as that would solve all your problems (and may your queries safer). Check the examples in the manual http://php.net/manual/en/mysqli-stmt.bind-param.php

Query working in PHPMyAdmin but not in PHP

I am new to PHP and I have taken up an online tutorial, till now I had been working fine but now my database is not returning the query, though when I go to PHPmyadmin there I can get the query working fine.
Following is the code
<?php
ob_start();
//Delete Item question to admin and delete product
include"../storescripts/connect_to_mysql.php";
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete the item with ID '.$_GET['deleteid'].'?Yes|No';
exit();
}
if(isset($_GET['yesdelete'])){
// Delete the actual product and delete picture also
//delete from database
//$id_to_delete = $_GET['yesdelete'];
//echo $id_to_delete;
$sql =mysqli_query( "DELETE * FROM `products` WHERE `id`=2 LIMIT1 ");
//mysql_query("DELETE * FROM `products` WHERE `id`='$id_to_delete'LIMIT1") or (mysql_error());
//mysqli_query("DELETE * FROM products WHERE id=`$id_to_delete`LIMIT1");// or (mysql_error());
//Unlink file from server
$pictodelete=("../inventory_images/$id_to_delete");
//echo $pictodelete;
if(file_exists($pictodelete)){
unlink($pictodelete);
}
header("location:inventory_list.php");
exit();
}
?>
I would really appreciate the help, my server reads PHP Extension :mysqli .
i dont know what is inside connect_to_mysql.php but at first there is a procedure to connect to a database which i am assuming that you have done correctly, it consist of code which looks something like that at default settings
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename="abc";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$databasename);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
the second things i see in your code
$sql =mysqli_query( "DELETE * FROM `products` WHERE `id`=2 LIMIT1 ");
it contains syntax errors,it should be
$sql =mysqli_query( $conn,"DELETE FROM `products` WHERE `id`=2 LIMIT 1 ");
A space after Limit.
You have not specified the connection in mysqli_query() function.
eg:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
In your case
$sql =mysqli_query( $connectionname,"DELETE * FROM `products` WHERE `id`=2 LIMIT 1 ");
Error at query : $sql =mysqli_query( "DELETE * FROM products WHERE id=2 LIMIT1 ");
replace DELETE * FROM products with DELETE FROM products.DELETE delete row from table.
Procedure like mysqli_query takes at least two argument
Link identifier returned form mysqli_connect
Query string
And you haven't specified link as first arguments you should use returned link in to mysqi_query.
$con = mysqli_connect('localhost','root','password','db');
$sql =mysqli_query( $con,"DELETE FROM `products` WHERE `id`=2 LIMIT1 ");
This link helps you link mysqli_query

PHP MySQL inserting information from one form into multiple tables

So I have form1 that contains information from multiple tables in a database. I've got listboxes and textboxes within this form that have that information. So all I'm trying to do is insert whatever information the user submits back into the database and have it outputted on form2. I've got my INSERT INTOs on my output page. I know you can't use one INSERT INTO query, so I was wondering how to use multiple INSERTS and submit that information back into the database.
The variables created below come from the previous page and all of the values are there.
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
echo "New record created successfully";
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query = "select status_id from ostatus where status_type = '$ostatus'";
$result = mysqli_query($db, $query) or die("Error in SQL statement:" .mysqli_error());
$row = mysqli_fetch_array($result);
$statusid = $row[0];
$query1 = "insert into cust ('c_fname', 'c_lname') values ('$cfname', $clname)";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed ('e_fname', e_lname) values ('$efname', '$elname')";
$result2 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('{$oid}', '{$odate}', '{$statusid}')";
$result3 = mysqli_query($db, $query3);
}
First of all your query is vulnerable to SQL injection. I am not going to fix that.
Second, you should Google how to handle forms properly. And you should consider starting SQL transaction if you really care about the data to go into all the tables for sure.
Third, you should be able to use multiple inserts like you are doing in your code. but you need to correct your syntax errors.
Try this code (I also removed the select code are based on your question it is not needed)
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query1 = "insert into cust (c_fname, c_lname) values ('".$cfname."', '".$clname."')";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed (e_fname, e_lname) values ('".$efname."', '".$elname."')";
$result2 = mysqli_query($db, $query2) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('".$oid."', '".$odate."', '".$statusid."')";
$result3 = mysqli_query($db, $query3);
if($result1 && $result2 && $result3)
echo 'New record created successfully';
else
echo 'something did not work';
}

Update SQL database PHP

I have a form that posts variables back from a drop down list in php. I then need to take those values and update my database values for each "TeamName". I am using the following code but nothing is updating.
$g1 = mysql_real_escape_string($_POST['g1']);
$conn = mysql_connect("****.com","****","*****") or die("Connection to MYSQL");
mysql_select_db("****_teamlist", $conn) or die("Connection to MYSQL database failed");
$sSQL = "UPDATE Sheet1 Set g1='$g1' WHERE TeamName = 'TeamName' ";
$result = mysql_query($sSQL, $conn) or die(mysql_error());
Where is my error? I am stuck.

PHP: mysqli_query is not working [duplicate]

This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";

Categories