This question already has answers here:
How to execute two mysql queries as one in PHP/MYSQL?
(8 answers)
Closed 8 years ago.
The SQL code used below works just fine if pasted in PHPMyAdmin.
But once I use it in custom PHP code it throws an exception:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'CREATE TABLE v2_session ( username varchar(150) DEFAULT '', time
varchar(1' at line 2
What am I missing, the code is dead simple, I am so confused right now.
This is my PHP code:
$con=mysqli_connect("host","user","password","db");
if (mysqli_connect_errno()) {
echo "Error: " . mysqli_connect_error();
}
$sql="
DROP TABLE IF EXISTS v2_session;
CREATE TABLE v2_session (
username varchar(150) DEFAULT '',
time varchar(14) DEFAULT '',
session_id varchar(200) NOT NULL DEFAULT '0',
guest tinyint(4) DEFAULT '1',
userid int(11) DEFAULT '0',
usertype varchar(50) DEFAULT '',
gid tinyint(3) unsigned NOT NULL DEFAULT '0',
client_id tinyint(3) unsigned NOT NULL DEFAULT '0',
data longtext,
PRIMARY KEY (session_id(64)),
KEY whosonline (guest,usertype),
KEY userid (userid),
KEY time (time)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
if (mysqli_query($con,$sql)) {
echo 'Success!';
} else {
echo "Error: " . mysqli_error($con);
}
mysqli_close($con);
mysqli_query does not allow for multiple statements concatenated by a semicolon.
Either split the query up into two separate queries, or use mysqli_multi_query() with a very similar syntax instead.
bool mysqli_multi_query ( mysqli $link , string $query )
Executes one or multiple queries which are concatenated by a semicolon.
The downside with mysqli_multi_query is that it makes your code more sensitive to SQL injection (since a whole statement can be injected), but for static queries without parameters it should not cause any problems.
These are two statements, and should be executed separately:
$sql = "DROP TABLE IF EXISTS v2_session";
if (!mysqli_query($con,$sql)) {
echo "Error: " . mysqli_error($con);
exit(1);
}
$sql="
CREATE TABLE v2_session (
username varchar(150) DEFAULT '',
time varchar(14) DEFAULT '',
session_id varchar(200) NOT NULL DEFAULT '0',
guest tinyint(4) DEFAULT '1',
userid int(11) DEFAULT '0',
usertype varchar(50) DEFAULT '',
gid tinyint(3) unsigned NOT NULL DEFAULT '0',
client_id tinyint(3) unsigned NOT NULL DEFAULT '0',
data longtext,
PRIMARY KEY (session_id(64)),
KEY whosonline (guest,usertype),
KEY userid (userid),
KEY time (time)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
if (mysqli_query($con,$sql)) {
echo 'Success!';
} else {
echo "Error: " . mysqli_error($con);
}
Related
I'm trying to create following table . query works in phpmyadmin but doesn't work in php script. pls point out mistake in my code. Thank You
$sql = "CREATE TABLE IF NOT EXISTS `portal` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`message_sid` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`number` varchar(255) NOT NULL,
`message` text NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`status` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1";
if (mysqli_query($conn, $sql)) {
echo "Table portal created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
I'm getting this error:
You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the
right syntax to use near '`id` int(255) NOT NULL AUTO_INCREMENT,
`message_sid` varchar(255) NOT NULL' at line 2
I have done this by checking if table exists in php, on false create a new table
creating table would be best to export an already existing one with phpmyadmin and then just use it as query syntax
Take the single quotes off of your table and row names
also if you make the id a primary key auto-increment, do not make it not null, this will cause a error.
I am unsure why the down votes....
CREATE TABLE IF NOT EXISTS portal (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
message_id VARCHAR(30) NOT NULL,
name VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
number VARCHAR(50) NOT NULL,
message text NOT NULL,
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(50) NOT NULL )ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1
This will work
I'm trying to make some SQL commands in XAMPP. My query returns following error:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'CREATE TABLE IF NOT EXISTS kayttajat ( id INT(10) NOT NULL
AUTO_INCREMENT, tunn' at line 2
I can't find the syntax error. And when I run the exact same command by copy-paste in command line, it works. So do I need some different syntax in PHP code?
Also if I remove the first command, the error message moves to [...] right syntax to use near 'CREATE TABLE IF NOT EXISTS rivit [...]. If I remove second command the error comes from third command and so on. I really don't understand where the error is.
$query='
CREATE DATABASE IF NOT EXISTS asdgfhj;
CREATE TABLE IF NOT EXISTS kayttajat
(
id INT(10) NOT NULL AUTO_INCREMENT,
tunnus1 varchar(32) NOT NULL,
tunnus2 varchar(32) NOT NULL,
nimi varchar(32),
nimi2 varchar(32),
oikeus INT(10) NOT NULL DEFAULT 1,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS rivit
(
id INT(10) NOT NULL AUTO_INCREMENT,
sivu INT(10) NOT NULL,
kayttaja INT(10) NOT NULL,
sana varchar(500),
kommentti varchar(1000),
aika TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
muutos TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS sivut
(
id INT(10) NOT NULL AUTO_INCREMENT,
nimi varchar(32) NOT NULL,
ohje varchar(2000) NOT NULL,
salaisuus INT(10) NOT NULL DEFAULT 1,
PRIMARY KEY(id)
);
';
$mysqli->query($query) or die($mysqli->error);
The query() method is designed to execute a single query not multiple ones.
What you are looking for is multi_query() to execute multiple queries separated by a semicolon.
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
...
}
You should use multi_query if you want execute many queries with one command.
Also you don't select database which will used for insert statements.
You should add asdgfhj prefix for all tables or use USE asdgfhj after create table statement.
example with prefix:
<?php
$query='
CREATE DATABASE IF NOT EXISTS asdgfhj;
CREATE TABLE IF NOT EXISTS asdgfhj.kayttajat
(
id INT(10) NOT NULL AUTO_INCREMENT,
tunnus1 varchar(32) NOT NULL,
tunnus2 varchar(32) NOT NULL,
nimi varchar(32),
nimi2 varchar(32),
oikeus INT(10) NOT NULL DEFAULT 1,
PRIMARY KEY (id)
);
';
$mysqli->multi_query($query) or die($mysqli->error);
example with use statement:
<?php
$query='
CREATE DATABASE IF NOT EXISTS asdgfhj;
USE asdgfhj;
CREATE TABLE IF NOT EXISTS kayttajat
(
id INT(10) NOT NULL AUTO_INCREMENT,
tunnus1 varchar(32) NOT NULL,
tunnus2 varchar(32) NOT NULL,
nimi varchar(32),
nimi2 varchar(32),
oikeus INT(10) NOT NULL DEFAULT 1,
PRIMARY KEY (id)
);
';
$mysqli->multi_query($query) or die($mysqli->error);
I'm trying to insert some date to MySQL table with prepared insert with nested 3 nested selects in it. The thing is that for all nested selects a single variable is used. Actual SQL:
INSERT INTO db_test.offers
(`id`,`catalog_service_id`,`offer_name`,
`offer_description`,`offer_url`,
`offer_interaction_format`,`offer_methods`)
VALUES(1,
(SELECT `catalog_service_id` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
(SELECT `catalog_service_name` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
(SELECT `catalog_service_name` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
'https://url.com', 'json', 'CC');
PHP code:
class test extends mysqli{
function db_action($host = null){
$mysqli = new mysqli($host, MYSQL_USER, MYSQL_PASS, "db_test");
if(!$mysqli){
die ("couldn't connect to mysql host" . mysqli_connect_error());
}
$codes= ["AAAAA005760000000001","ААААА032680000000001","ААААА032680000000002"];
$query="SQL code from above";
$stmt = $mysqli->prepare($query);
$stmt ->bind_param("sss", $offer, $offer, $offer);
foreach ($codes as $k => $offer) {
if($stmt->execute() === false){
print 'Wrong SQL. Error: ' . $stmt->error . "\r\n";
}else{
$last_inserted_id = $mysqli->insert_id;
print "Insert row with id: " . $last_inserted_id . " for service_code: ". $offer . "\r\n";
}
}
$stmt->close();
}
}
First iteration of foreach works fine (1 row is inserted with correct data), but on 2nd and 3rd (just for an example, real number of elements in $codes array is unknown). The The executed statement on the sql-server is executed with question marks instead of actual value. When I go through the function in debugger - the value of $offer var changes on each iteration of for each.
SQL error that comes from the server is obvious: catalog_service_id cannot be null.
table info:
CREATE TABLE `offers` (
`offer_id` int(11) NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL,
`catalog_service_id` int(11) NOT NULL,
`offer_name` varchar(255) DEFAULT NULL,
`offer_description` varchar(1000) DEFAULT NULL,
`offer_create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`offer_start_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`offer_stop_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`offer_url` varchar(256) NOT NULL,
`offer_auth` enum('Basic','Digest') DEFAULT NULL,
`offer_auth_name` varchar(255) DEFAULT NULL,
`offer_auth_password` varchar(255) DEFAULT NULL,
`offer_auth_secret` varchar(255) DEFAULT NULL,
`offer_operator_id` int(11) NOT NULL,
`public_offer_url` varchar(1000) NOT NULL,
`offer_interaction_format` enum('urlencoded','json') NOT NULL DEFAULT 'urlencoded',
`offer_methods` enum('CC','MC') NOT NULL DEFAULT 'MC',
`offer_inn` varchar(20) DEFAULT NULL,
`offer_kpp` varchar(20) DEFAULT NULL,
`offer_min` int(11) DEFAULT NULL,
`offer_max` int(11) DEFAULT NULL,
PRIMARY KEY (`offer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
I'm really stuck...
<?php
$ll=mysql_query("CREATE TABLE IF NOT EXISTS p (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`colum` varchar(255) NOT NULL DEFAULT '',
`ord` varchar(255) NOT NULL DEFAULT '',
`tex` varchar(255) NOT NULL DEFAULT '',
`search` varchar(255) NOT NULL DEFAULT '',
`count` varchar(255) NOT NULL DEFAULT '',
`order` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g');") or die(mysql_error()) ;
if($ll){
echo "insert AND CREATE ";}
else {echo "fail"; }
?>
I am working in a php language . In this page if the table is not created 1st create it and then insert the values into the column
After creating the table , I am inserting the values into the table but it showing me the error in the insert query
I am getting a this error- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO p VALUES ('count','name','asc','1','search','count','order ')' at line 11
what am i doing wrong
I am not absolutly sure if that is the problem but you are passing 7 values in your INSERT statement while your table deffinition has 8 fields.
I assume you are doing that because 'id' field is autoincremental. However, if that is the case, you should specify which columns correspond with your values in the insert statement:
INSERT INTO $p (title, column, ord, ...) VALUES ('$a','$b','$c','$d','$f','$h','$g')
Here is a dry run seperating the two statements - should work:
<?php
$querys[]="CREATE TABLE IF NOT EXISTS $p (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`colum` varchar(255) NOT NULL DEFAULT '',
`ord` varchar(255) NOT NULL DEFAULT '',
`tex` varchar(255) NOT NULL DEFAULT '',
`search` varchar(255) NOT NULL DEFAULT '',
`count` varchar(255) NOT NULL DEFAULT '',
`order` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1";
$querys[]="INSERT INTO $p VALUES (null,'$a','{$b}','{$c}','{$d}','{$f}','{$h}','{$g}')";
foreach($querys as $sql) {
$ll = mysql_query($sql);
$error=mysql_error();
if($error!='') {
print $sql."\n";
die($error);
}
}
?>
INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g')
should be
INSERT INTO p (`title`,`colum`,`ord`,`tex`,`search`,`count`,`order`) VALUES ('$a','$b','$c','$d','$f','$h','$g')
Hence order is a mysql keyword
you have ended the insert statement with a " double quote but not started you can write either
INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g');
or you can write
("INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g')");
try it in your code
note - please do not use mysqli and mysql in same code, rather you can use mysqli PDO
I am trying to read from a database in MySQL and insert my data in another database in MySQL .
my first table is like this
CREATE TABLE IF NOT EXISTS `link` (
`_id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(30) COLLATE utf8 DEFAULT NULL,
`time` varchar(20) COLLATE utf8 DEFAULT NULL,
`link` varchar(100) COLLATE utf8 DEFAULT NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6149 ;
and the second table is
CREATE TABLE IF NOT EXISTS `country` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(15) CHARACTER SET utf8 NOT NULL,
`Logo` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Name_3` (`Name`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8457 ;
There are about 6114 rows in first table that I'm trying to insert to second using this code
<?php
$tmp = mysqli_connect(******, *****, ****, *****); // First table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$main = mysqli_connect(*****, *****, ****, ******); //Second table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$req = "SELECT country FROM link";
$result = mysqli_query($tmp, $req) or die( mysqli_error($tmp) );
echo "-> ".mysqli_num_rows($result)."<br>";
while ($row = mysqli_fetch_array($result)) {
$con = $row["country"];
$req = "INSERT IGNORE INTO country (Name) VALUES ('$con')";
mysqli_query($main, $req) or die( mysqli_error($main) ) ;
}
?>
problem is the php code works but for 6114 take a very long time which I can't afford .
what is causing the code to take this long to work ? is it the "INSERT IGNORE" ?
is there any way I can do this faster ?
Since the databases are on the same server, you can simply use INSERT ... SELECT (which avoids having to bring the data into PHP and loop over the results executing separate database commands for each of them, so will be considerably faster):
INSERT INTO db2.country (Name) SELECT country FROM db1.link
you can try a create an index on column "country" of table Link.