I have a mysql database with a table "tb"
Column Type
---------------------------------
id int(11)
chainid int(11)
commission decimal(10,2)
order_count int(11)
total_order_value decimal(10,2)
fromdt date
todt date
I run this code from my php file
$query = "DELETE FROM `tb` WHERE chainid=$row[0];";
error_log("1st : ".$query);
$storeit = mysql_query($query);
error_log("result of query : ".$storeit);
$query = "INSERT INTO `tb` VALUES(null,$row[0],$com,$oc,$ov,'$startdate','$enddate');";
error_log("2nd : ".$query);
$storeit = mysql_query($query);
error_log("result of query : ".$storeit);
but there's nothing happens in DB, and the prints in error_log was:
1st : DELETE FROM tb WHERE chainid=4 AND
fromdt='2017-05-01' AND todt='2017-05-31';
result of query :
INSERT INTO tb
VALUES(null,4,4755.69,94,6793.84,'2017-05-01','2017-05-31');
result of query :
while when I use these two sentences:
DELETE FROM `tb` WHERE chainid=4 AND fromdt='2017-05-01' AND todt='2017-05-31';
INSERT INTO `tb` VALUES(null,4,4755.69,94,6793.84,'2017-05-01','2017-05-31');
in SQL tab in phpmyadmin they worked perfectly!!
So, I don't know what is wrong with my code? is there something I can do?
UPDATE
after using [tag:mysql_error()] from http://php.net/manual/en/function.mysql-error.php
function q($query){
$result = mysql_query($query);
if (mysql_errno()) {
$error = "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$query\n<br>";
error_log($error);
}
}
and called this function instead, using:
$query = "DELETE FROM `tb` WHERE chainid=$row[0] AND fromdt='$startdate' AND todt='$enddate';";
$result = q($query);
$query = "INSERT INTO `tb` VALUES(null,$row[0],$com,$oc,$ov,'$startdate','$enddate');";
$result = q($query);
I got these:
MySQL error 2014: Commands out of sync; you can't run this command now
When executing: DELETE FROM tb WHERE chainid=4 AND
fromdt='2017-05-01' AND todt='2017-05-31';
MySQL error 2014: Commands out of sync; you can't run this command now
When executing: INSERT INTO tb
VALUES(null,4,4755.69,94,6793.84,'2017-05-01','2017-05-31');
UPDATE 2
after a little search about:
Commands out of sync; you can't run this command now
in Commands out of sync; you can't run this command now SQL
I figured out that I have to close connection and start it again. but the problem is I'm using a function to connect database in the beginning of my function.php which included in my header.php file :
function db_connect()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
#mysql_connect($servername,$username,$password) or die ("error in host connection");
header('Content-Type: text/html; charset=utf-8');
mysql_set_charset('utf8_unicode_ci');
#mysql_select_db($dbname) or die("error in db connection");
mysql_query("SET NAMES 'utf8'");
}
db_connect();
So, how to close the connection using mysql_close(); ?
I just needed to close connection before mysql_query using:
mysql_close();
and open a connection again immediately using my function:
db_connect();
Many thanks to everyone who contributed trying to solve this problem.
Related
I'm still getting mysql error in my PHP script.
Problematic code:
$mquery = mysql_query("SELECT m.`id`, m.`name`, NULL AS `type`, NULL AS `code`, 0 AS `cat` FROM `menu` m UNION ALL SELECT l.`id`, l.`name`, l.`type`, l.`code`, l.`cat` FROM `lines` l UNION ALL SELECT s.`id`, s.`name`, s.`site`, s.`site`, s.`cat` FROM `sites` s ORDER BY `name` ASC");
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery)) { ... }
When i put this query into PhpMyAdmin - all is OK, i will get result. When I put this query into MySQL Workbench - all is OK, i will get result.
AND NOW: When I run script with parameter (http://domain/index.php?site=ABC) - ALL IS OK. When I run script without parameter (http://domain/index.php) - I get mysql error on this query: "Table 'test.menu' doesn't exist".
What "test.menu"?! Where is "test"? I don't want any "test", I have no "test" in my query. And why is it related on parameter in url? It's not dynamically generated query. Where is problem?
Sorry for my english
Solved, script structure:
$mydb = mysql_connect(...);
mysql_select_db(..., $mydb);
mysql_set_charset('utf8', $mydb);
function newMenu($db)
{
$mquery = mysql_query("...", $db);
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery) { ... }
}
myMenu($mydb);
But what i don't understand is: Why is it working without "$db" when parameter 'site' is in url?
Please check your mysql configuration in PHP. I am pretty sure you are using database name as 'test' because you've copied the code from somewhere. Change it to the actual name of your database and it will work.
The second parameter of mysql_query must be a connection variable.
<?php
$con = mysql_connect("localhost", "root", "mypass") or
die("Could not connect: " . mysql_error());
mysql_select_db("tutorials");
$result = mysql_query("select * from tutorials");
echo "<h2>Here is a list of the topics:</h2>";
while ($row = mysql_fetch_array($result)) {
echo $row['name']."<br />";
}
mysql_close($con);
?>
Could you give full php script? is the database config related to 'site' parameter ?
Don't know if someone can help but for some reason when using call stored procedure that has a select before a dynamic SQL syntax error PHP doesn't report an error. If calling the stored procedure in workbench the error shows.
Basic setup MySQL:
create table testtable (testcolumn varchar(10), PRIMARY KEY (testcolumn));
DELIMITER ///
CREATE PROCEDURE teststoredproc ()
BEGIN
SELECT 'Select text';
SET #sql := 'SELECT * FROM testtable WHERE IFNULL(DATE(testcolumn), ''1900/01/01'' = DATE(''1900/01/01'')';
PREPARE stmtteststoredproc FROM #sql;
EXECUTE stmtteststoredproc;
DEALLOCATE PREPARE stmtteststoredproc;
END
DELIMITER ;
Basic setup php
<?php
$DB_NAME = '';
$DB_HOST = '';
$DB_USER = '';
$DB_PASS = '';
$mysqli = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = mysqli_query($mysqli, "CALL teststoredproc();") or die("Query fail: " . mysqli_error());
while ($row = mysqli_fetch_array($result)){
echo $row[0];
}
?>
Now instead of the die executing because there is a syntax error in the dymanic SQL, the while will run and echo 'Select text'.
The question is how do I correctly handle mysql stored procedure calls in php so that I will get the errors no matter the amount of selects, etc before the error happens?
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'";
I am trying to get the top 10 items from a table:
<?php
include DBConnect.php;
$dbname = 'Telejoke';
mysql_select_db($dbname);
$query = "SELECT * FROM jokes LIMIT 10";
$data = mysql_query($query) or die('Error, insert query failed');
mysql_close($conn);
$info = mysql_fetch_array( $data );
?>
The PHP script keeps executing the die part saying that my query insert failed.
UPDATE:
The error is No connection could be made because the target machine actively refused it.
UPDATE 2:
I think the user I connect to DB is not authorized to use the SELECT command. This would cause the preceding error?
In db connection.php you must use a user name with password who is allowed to do operations on db.
I have a simple script which I have included here. the select query works fine but the insert query fails. I am running php, apache and mysql on my macbook.
The table city_profile has ID as a auto increment primary key. And name is a non-null.
function testMySQL() {
$db = new mysqli('localhost', 'root', NULL, 'citee');
//$query = "select * from city_profile"; //this query works
$query = "insert into city_profile ('name','state','country') values ('charlotte','north carolina','usa')";
//whereas the above one fails..
$results = $db->query($query);
if($results) {
echo '<p>The query is successful.</p>';
}else {
echo '<p>The query is NOT successful.</p>';
}
//close the connection
$db->close();
}
try to change this line:
$query = "insert into city_profile ('name','state','country') values ('charlotte','north carolina','usa')";
into this:
$query = "insert into `city_profile` (`name`,`state`,`country`) values ('charlotte','north carolina','usa')";