Syntax error with SQL in PHP - php

I'm trying to set the column of a table to a string in every row if the column exists. However, I am receiving SQL syntax errors and can't pinpoint what exactly the issue is:
while($db = mysqli_fetch_array(mysqli_query($conn, "SHOW DATABASES"))){
$id = $db['id'];
$sql = /** #lang text */
"SELECT IF( EXISTS(
SELECT DISTINCT `info`
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('borrower')
AND TABLE_SCHEMA = '$db'))
BEGIN
UPDATE `info`
SET `borrower` = '****'
WHERE `id` = '$id'
END";
$query = mysqli_query($conn, $sql);
if (!$query){
// Deal with error
}
}
The syntax error I receive back:
information_schemadb1You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')BEGINUPDATE infoSET borrower = '****'' at line 5
I know it must be something very small but I have been stuck for a while and can't seem to find my error.

Try this syntax for the query-
IF EXISTS (SELECT DISTINCT `info`
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('borrower')
AND TABLE_SCHEMA = '$db')) THEN
UPDATE `info`
SET `borrower` = '****'
WHERE `id` = '$id'
END IF;
I added Then in the end of the if condition and End if instead of only if, and I removed the select to. What are you trying to select? it is only update clause.
update
Example from here
you can't use it like a normal query. Control structures like IF or
WHILE are only allowed in stored procedures or functions.
MYSQL panel
delimiter $$
create procedure YourIfConditionSP()
begin
IF EXISTS (SELECT DISTINCT `info`
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('borrower')
AND TABLE_SCHEMA = '$db') THEN
UPDATE `info`
SET `borrower` = '****'
WHERE `id` = '$id';
END IF;
end $$
delimiter ;
And you have to change your php code for calling the stored procedure.
PHP
//run the stored procedure
$result = mysqli_query($connection,
"CALL YourIfConditionSP") or die("Query fail: " . mysqli_error());
How to call a MySQL stored procedure from within PHP code?

Related

What is Wrong with this SQL Syntax that checks if a table exists?

I'm querying a server and iterating through multiple databases using PHP, but for some reason this $sql2 query (which I have read works in countless threads) is returning a syntax error:
$res = mysqli_query($conn,"SHOW DATABASES");
if (!$res){
// Deal with error
}
while ($d = mysqli_fetch_array($res)){
$db = $d['Database'];
$sql1 = "USE $db";
$query1 = mysqli_query($conn, $sql1);
if (!$query1){
// Deal with error
}
$sql2 = "IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLE
WHERE TABLE_SCHEMA = '$db'
AND TABLE_NAME = 'appusers'))
BEGIN
SELECT * FROM `appusers`
END";
$query2 = mysqli_query($conn, $sql2);
if (!$query2){
// Deal with error
}
}
This is the error I receive:
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 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE WHERE TABLE_S' at line 1
My MySQL Server version is 5.6.27 and my PHP interpreter is 5.6
You can't use an IF statement as a query, only in a stored procedure. You'll need to perform two separate queries.
$sql = "SELECT COUNT(*) AS count
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '$db'
AND TABLE_NAME = 'appusers'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn);
$row = mysqli_fetch_assoc($result);
if ($row['count'] != 0) {
$sql2 = "SELECT * FROM appusers";
$query2 = mysqli_query($conn, $sql2);
...
} else {
// deal with error
}
There is no if in SQL (although mysql has a function called if)
Apparently, you want to run a query if the table exists. The more common way would be to try running the query and check whether the error you get says that the table doesn't exist.
E.g. if you run the query in the mysql command line application, you might get this:
mysql> SELECT * FROM appusers;
ERROR 1146 (42S02): Table 'test.appusers' doesn't exist
You see two codes:
1146: internal mysql code (obtain this via mysqli_errno)
42S02: the SQL standard error state (obtain this via mysqli_sqlstate)
In your case, checking the SQL state might be better because it covers more cases. E.g., all of these mysql error codes map to SQL state 42S02:
1051 - Unknown table '%s'
1109 - Unknown table '%s' in %s
1146 - Table '%s.%s' doesn't exist

mysqli query gets syntax error but phpmyadmin works

While the following query works with phpmyadmin, when I use mysqli->query(), a syntax error occurs
START TRANSACTION;
SELECT Value INTO #Increment FROM SystemConfiguration WHERE `Key` = 'POIncrement' FOR UPDATE;
UPDATE SystemConfiguration SET Value = Value + #Increment WHERE `Key` = 'POID';
COMMIT;
The syntax error message:
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 'SELECT Value INTO #Increment FROM SystemConfiguration WHERE `Key` = 'POIncrement' at line 2
Is it that mysqli prepares the query and adds something in?
$sql = <<<SQL
START TRANSACTION;
SELECT Value
INTO #Increment
FROM SystemConfiguration
WHERE `Key` = 'POIncrement' FOR UPDATE;
UPDATE SystemConfiguration
SET Value = Value + #Increment
WHERE `Key` = 'POID';
COMMIT;
SQL;
$res = mysqli_multi_query($connection, $sql);

Is it possible to select certain elements of the database table?

For example: I have a table name tbl_admin and I have so many table elements within that table.
Like (id, fname, lname, contact_info, email, ip, date, status, etc.and so on upto 20 elements).
Now I need to exclude only 3 elements from that table as you can say (fname, lname and contact_info) and select all others. Is this possible by using the mysql query?
Please help me if this is possible. Thanks,
Short Answer
You can't exclude columns explicitly, but you can do so implicitly by selecting only the other columns:
SELECT
ID,
EMAIL,
IP,
DATE,
STATUS
FROM tbl_admin
Long Answer
It turns out I was wrong with the short answer, technically there is a way as illustrated with the question here.
To do this in PHP, I'd recommend creating a view in the MySQL database that would encapsulate the SQL. Then you would just select * from that view.
Alternatively, you could create a stored procedure, and pass in the names of the columns that you want to be filtered out.
Try:
$result = mysql_query("SHOW COLUMNS FROM tbl_admin");
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$columns[] = $row['Field'];
}
}
//fill all columns here that you want to exclude
$columns_to_exclude = array('fname','lname','contact_info');
$sql = "SELECT (";
foreach($columns as $ind=>$val){
if(!in_array($val,$columns_to_exclude))
{
$sql .= $val.", ";
}
}
$sql = rtrim($sql,", ");
$sql .= ") FROM tbl_admin;";
echo $sql;
Select fname,sname,contact from table_admin
Yes, so you will have something like this:
SELECT
id,
fname,
lanem
FROM
tbl_admin
You just need to specify what are those and in what order. Instead of using the * to fetch all records (columns) in its default order.
Edit
SET #sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
Actually, I just got it from another's posts so all credits goes to him. HERE
Latest Answer
ANSWER BY Mahomedalid in Select all columns except one in MySQL?
SET #sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
For your situation replace the <columns_to_omit> with fname,lname,contact_info
Old Answer
Syntax for retrieving particular column values from table is
SELECT column_name(s)
FROM table_name
All columns can be retrieved using SELECT * instead of SELECT column_name(s)
if you are directing your question towards a particular language like PHP then the syntax can be like this
<?php
$con=mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT fname,lname,contact_info FROM tbl_admin");?>

PHP error get value from database

I have php script like this
$query = "select * where userid = 'agusza' ";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
echo $result;
}
when I execute, the result like this
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 'where userid = 'agusza'' at line 1
But when I run that sql in sqlserver, it running well
Anybody has solution ?
$query = "select * from table_name where userid = 'agusza' ";
See the corrections I have made. You haven't used the right syntax for SELECT query
You didn't select a table using FROM. Without that, it does not know which table you are selecting data from.
You should also stop using mysql as it is deprecated. Use mysqli or PDO as they are safer.
You are also echoing the wrong variable in your while loop, try this:
while ($row = mysql_fetch_array($result) {
echo $row['column_name'];
}
$query = "select * from table where userid = 'agusza'";
Right now, you're not telling which table SQL should look in.
You should format your query like so:
select * from `TableName` where userid='agusza'
In your query below you doesnt state the database table where you should get that data using FROM
$query = "select * where userid = 'agusza' "; // instead of this
$query = "select * FROM declaredtable where userid = 'agusza' "; used this

make a temporary table and select from it

I'm getting an error 'undeclared variable: temp' when I run this...
<?php
$maketemp = "CREATE TEMPORARY TABLE temp(`itineraryId` int NOT NULL, `live` varchar(1), `shipCode` varchar(10), `description` text, `duration` varchar(10), PRIMARY KEY(itineraryId))";
mysql_query( $maketemp, $connection ) or die ( "Sql error : " . mysql_error ( ) );
$inserttemp = "SELECT live, id AS itineraryId, ship AS shipCode, description AS description, duration AS length FROM cruises WHERE live ='Y' INTO temp";
mysql_query( $inserttemp, $connection ) or die ( "Sql error : " . mysql_error ( ) );
$select = "SELECT intineraryId, shipCode, description, duration FROM temp";
$export = mysql_query ( $select, $connection ) or die ( "Sql error : " . mysql_error( ) );
Any ideas ?
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This code should work:
<?php
$maketemp = "
CREATE TEMPORARY TABLE temp_table_1 (
`itineraryId` int NOT NULL,
`live` varchar(1),
`shipCode` varchar(10),
`description` text,
`duration` varchar(10),
PRIMARY KEY(itineraryId)
)
";
mysql_query($maketemp, $connection) or die ("Sql error : ".mysql_error());
$inserttemp = "
INSERT INTO temp_table_1
(`itineraryId`, `live`, `shipCode`, `description`, `duration`)
SELECT `id`, `live`, `ship`, `description`, `duration`
FROM `cruises`
WHERE `live` = 'Y'
";
mysql_query($inserttemp, $connection) or die ("Sql error : ".mysql_error());
$select = "
SELECT `itineraryId`, `shipCode`, `description`, `duration`
FROM temp_table_1
";
$export = mysql_query($select, $connection) or die ("Sql error : ".mysql_error());
I guess you are going to do more stuff with the temporary table, or are just playing with it, but if not be aware that the whole code could be summed up with:
<?php
$query = "
SELECT `id` AS 'itineraryId', `ship`, `description`, `duration`
FROM `cruises`
WHERE `live` = 'Y'
";
$export = mysql_query($query, $connection) or die ("Sql error : ".mysql_error());
I like to use heredoc to help me construct embedded sql query (just to help make any subtle error glaring); so your first query would look something like this:
$maketemp =<<<s
CREATE TEMPORARY TABLE temp(
`itineraryId` int NOT NULL,
`live` varchar(1),
`shipCode` varchar(10),
`description` text,
`duration` varchar(10),
PRIMARY KEY(itineraryId));
s;
Then if you want to correct the 2nd query without listing the fields of the table you want to insert the records, you have to list the fields in the same order.
Just the query this time:
INSERT INTO temp
SELECT id, live, ship, description, duration
FROM cruises
WHERE live = 'y';
And last thing about temporary variable is this: Check out the part about its visibility.
You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed.
http://dev.mysql.com/doc/refman/5.5/en/create-table.html
What that means is this: when you're connected to MySQL directly, e.g. through a command line interface like this:
mysql> #our query here line-by-line
Then you're essentially on the same connection through all of your multiple queries as long as your session is active.
But in an external script (like PHP, for example), just because it's on the same script file doesn't necessarily mean it's the same connection so that by the time you execute your insert query, your temp table is not visible to that connection session.
Try to concat all the queries, send it all within a single command/query execution.
Good luck.
The second query is not correct.
From the reference -
MySQL Server doesn't support the SELECT ... INTO TABLE Sybase SQL
extension. Instead, MySQL Server supports the INSERT INTO ... SELECT.
standard SQL syntax, which is basically the same thing.
Try this one instead -
INSERT INTO temp
SELECT live
, id AS itineraryId
, ship AS shipCode
, description AS description
, duration AS length
FROM
cruises
WHERE
live = 'Y'

Categories