why am i getting sql error 0 with mysql 8? [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 2 years ago.
i can't seem to figure it out why i'm getting this error i am using percona server for mysql 8 with sql mode set to sql_mode = "NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
this is the error i am getting whats sql error 0 ?
MySQL: Invalid Query:
SELECT
Rank,
SpecialRank,
TotalRank,
DonationTime,
RankExpirationTime + INTERVAL 766 HOUR
FROM users_donor_ranks
WHERE UserID = '1' SQL error: 0 ()
the sql table that i am using
CREATE TABLE `users_donor_ranks` (
`UserID` int(10) NOT NULL DEFAULT '0',
`Rank` tinyint(2) NOT NULL DEFAULT '0',
`DonationTime` datetime DEFAULT NULL,
`Hidden` tinyint(2) NOT NULL DEFAULT '0',
`TotalRank` int(10) NOT NULL DEFAULT '0',
`SpecialRank` tinyint(2) DEFAULT '0',
`InvitesRecievedRank` tinyint(4) DEFAULT '0',
`RankExpirationTime` datetime DEFAULT NULL,
PRIMARY KEY (`UserID`),
KEY `DonationTime` (`DonationTime`),
KEY `SpecialRank` (`SpecialRank`),
KEY `Rank` (`Rank`),
KEY `TotalRank` (`TotalRank`)
) ENGINE=InnoDB CHARSET=utf8mb4;
the query i am making
G::$DB->query("
SELECT
Rank,
SpecialRank,
TotalRank,
DonationTime,
RankExpirationTime + INTERVAL 766 HOUR
FROM users_donor_ranks
WHERE UserID = '$UserID'");

RANK is a reserved word in MySQL starting version 8.0.2.
You would need to quote this identifier, using backticks:
SELECT
`Rank`,
SpecialRank,
TotalRank,
DonationTime,
RankExpirationTime + INTERVAL 766 HOUR
FROM users_donor_ranks
WHERE UserID = ?

Related

How to Run Timely Automated Query on MySQL

I have a field called pending and been declared as Boolean with default value of 0 as:
`pending` tinyint(1) NOT NULL DEFAULT '0'
I am running an Update query againt the database to change the state of qpending to 1 like below
$sql = "UPDATE `appointments` SET `pending` = '1' WHERE `appointments`.`id` = 124;
now my question is, is there any way to automatically re-state the pending to 0 after 30 minutes by taking a conditional clause like
// After 30 Minutes of update!
if (!confirmed){
$sql = "UPDATE `appointments` SET `pending` = '0' WHERE `appointments`.`id` = 124;
}
Table Schema
CREATE TABLE IF NOT EXISTS `appointments` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`date` varchar(100) CHARACTER SET utf8 NOT NULL,
`available` tinyint(1) NOT NULL DEFAULT '1',
`pending` tinyint(1) NOT NULL DEFAULT '0',
`confirmed` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
You are doing it wrong.
Make your pending field not a boolean but a datetime, with the value of the due time. Then in your select queries just compare that value with the current time. So instead of
SELECT * FROM appointments WHERE pending = 1
just make it
SELECT * FROM appointments WHERE pending < NOW()
this solution is either much simpler and more flexible

Execute multiple queries from file fast [duplicate]

This question already has answers here:
Running MySQL *.sql files in PHP
(15 answers)
Closed 7 years ago.
I have a file with queries. Something like that:
DROP TABLE IF EXISTS #__assets;
CREATE TABLE IF NOT EXISTS `#__assets` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary Key', `parent_id` int(11) NOT NULL DEFAULT '0' COMMENT 'Nested set parent.', `lft` int(11) NOT NULL DEFAULT '0' COMMENT 'Nested set lft.', `rgt` int(11) NOT NULL DEFAULT '0' COMMENT 'Nested set rgt.', `level` int(10) unsigned NOT NULL COMMENT 'The cached level in the nested tree.', `name` varchar(50) NOT NULL COMMENT 'The unique name for the asset.\n', `title` varchar(100) NOT NULL COMMENT 'The descriptive title for the asset.', `rules` varchar(5120) NOT NULL COMMENT 'JSON encoded access control.', PRIMARY KEY (`id`), UNIQUE KEY `idx_asset_name` (`name`), KEY `idx_lft_rgt` (`lft`,`rgt`), KEY `idx_parent_id` (`parent_id`) ) ENGINE=InnoDB AUTO_INCREMENT=92 DEFAULT CHARSET=utf8;
INSERT INTO #__assets VALUES("1","0","0","165","0","root.1","Root Asset","{\"core.login.site\":{\"6\":1,\"2\":1},\"core.login.admin\":{\"6\":1},\"core.login.offline\":{\"6\":1},\"core.admin\":{\"8\":1},\"core.manage\":{\"7\":1},\"core.create\":{\"6\":1,\"3\":1},\"core.delete\":{\"6\":1},\"core.edit\":{\"6\":1,\"4\":1},\"core.edit.state\":{\"6\":1,\"5\":1},\"core.edit.own\":{\"6\":1,\"3\":1}}");
...
And so...
I can split this file row by row and execute.
But this is slow as I have big file. Do you know any faster way to solve this problem?
Thanks!
Get file content in a variable as a string
and use mysqli_multi_query()
// condition the queries must be ; seprated
<?php
$queries = get_file_content("filename.sql/or_anyotherfile");
$result = mysqli_multi_query($con,$queries);
?>
something like this always works for me
you can execute them directly on server by below command, which will be fastest way-
mysql -u<user> -p<pass> db_name < file.sql

Can't execute multi-statement SQL through PHP code [duplicate]

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);
}

PDOException error in mysql SQL syntax [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am trying to create 2 tables in the same MySQL database with a PHP-script:
table 'user' with primary key 'user_id' and table 'order' with primary key 'order_id' and foreign key 'user_id' from the 'user' table (1 to many relationship).
Table user creates successfully without problems:
$sql="CREATE TABLE user(
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
type ENUM('member','admin') NOT NULL,
username VARCHAR(30) NOT NULL,
email VARCHAR(80) NOT NULL,
pass VARBINARY(32) NOT NULL,
first_name VARCHAR(40) NOT NULL,
last_name VARCHAR(40) NOT NULL,
date_expires DATE NOT NULL,
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
date_modified TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (user_id),
UNIQUE (username),
UNIQUE (email)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
However, I am not able to create table order:
$sql="CREATE TABLE order(
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
transaction_id VARCHAR(19) NOT NULL,
payment_status VARCHAR(15) NOT NULL,
payment_amount DECIMAL(6,2) UNSIGNED NOT NULL,
payment_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES user (user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
I get the following error:
Error creating table: 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 'order( order_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id ' at line 1
Already checked the syntax and cannot find the mistake. Could you please advise what went wrong? Thanks a lot.
You need to escape reserved words like order with backticks
CREATE TABLE `order` ( ...
or better use another name instead.
order is keyword used by mysql like (select from tbl_name order by id ASC) so for escaping from using keywords you have to use quotes `` to avoid my sql error
so your query should by
$sql="CREATE TABLE `order` (
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
transaction_id VARCHAR(19) NOT NULL,
payment_status VARCHAR(15) NOT NULL,
payment_amount DECIMAL(6,2) UNSIGNED NOT NULL,
payment_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES user (user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
enjoy :D

Delete data from two tables with INNER JOIN

I want to delete data from two tables with one SQL query according to datetime_lastactive and if the IP addresses is matching your own. But I'm getting this error message when I try out the following SQL query:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 'INNER JOIN visitors_main WHERE information_ipaddress = '123.123.123.123' A' at line 2' in ...
DELETE FROM visitors_list
INNER JOIN visitors_main
WHERE information_ipaddress = :ipaddress
AND datetime_lastactive < NOW() - INTERVAL 3 HOUR
The tables looks like this:
CREATE TABLE IF NOT EXISTS `visitors_list` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`id_visitor` int(10) DEFAULT '0',
`id_user` int(10) DEFAULT '0',
`data_filename` text NOT NULL,
`data_filename_get` text NOT NULL,
`data_useragent` text NOT NULL,
`datetime_lastactive` datetime NOT NULL,
`information_ipaddress` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
)
CREATE TABLE IF NOT EXISTS `visitors_main` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`id_user` int(10) DEFAULT '0',
`data_coordinates` varchar(25) NOT NULL,
`datetime_firstvisit` datetime NOT NULL,
`checkbox_anonymous` tinyint(4) DEFAULT '0',
`checkbox_tiecoordinates` tinyint(4) DEFAULT '0',
`checkbox_nogps` tinyint(4) DEFAULT '0',
`information_ipaddress` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
)
How can I make this work?
Try this instead:
DELETE l, m
FROM visitors_list AS l
INNER JOIN visitors_main AS m ON l.information_ipaddress = m.information_ipaddress
WHERE l.information_ipaddress = :ipaddress
AND l.datetime_lastactive < NOW() - INTERVAL 3 HOUR;
DELETE v1,v2
FROM visitors_list v1
INNER JOIN visitors_main v2 ON v1.id_visitor = v2.id
WHERE v1.information_ipaddress = :ipaddress
AND v1.datetime_lastactive < NOW() - INTERVAL 3 HOUR;

Categories