PHP Codeigniter: SQL syntax error `WHERE username = $username` - php

I try to add $username into MySQL query as follows. But the query fails with SQL syntax error.
$username = $this->input->post('username');
$sql = "SELECT * FROM temp_user UNION SELECT * FROM member WHERE username = ".$username."";
$query = $this->db->query($sql);
What's wrong with this query?
Here is error message Error Number: 1064
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 '' at line 1
SELECT * FROM temp_user UNION SELECT * FROM member WHERE username =
Filename: C:/xampp/htdocs/dex/system/database/DB_driver.php
Line Number: 691

Try it like this, no need for string concatenation
$sql = "SELECT * FROM temp_user UNION SELECT * FROM member WHERE username = '$username'";

The SQL syntax error is likely due to this part:
"... WHERE username = ".$username."";
You should escape $username
That is
"... WHERE username = ".$this->db->escape($username);
where $conn is a mysqli object representing the link identifier.

Solved!!! because of i cannot use star(*) with union
$sql = "SELECT username FROM temp_user WHERE username = '".$username."' UNION SELECT username FROM member WHERE username = '".$username."'";

Related

SQL syntax which sending me an Error

I have a Mysql Database named user. Here is a picture:
I want to change the Username of the user "dodlo.rg" programmatically.
Actually, I have the PHP-Version 7.1. And this is a part of my PHPCode:
EDITED CODE:
$newName= $_POST["changeT"];
$userId = $_POST["userId"];
$db = mysqli_connect("trolö", "trolö", "trolö123", "trolö")
$sql = "UPDATE user SET username = '$newName' WHERE user_id = '$userId'";
$query = mysqli_query($db, $sql);
$response["successU"] = true;
But I get the Error: "You gave an Error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM user' at line 1"
Thanks in advance.
The problem lies in 2 parts.
Firstly, since this column is a varchar field it needs to be inside quotes else it produces an sql error.
Secondly the SELECT statement just after is not valid, but i guess it was a copy/paste error.
Therefore your working code should be:
$newName= $_POST["changeT"];
$db = mysqli_connect("trolö", "trolö", "trolö123", "trolö")
$sql = "UPDATE user SET username = '".addslashes($newName)."' WHERE username = 'dodlo.rg'";
$query = mysqli_query($db, $sql);
$response["successU"] = true;
Also, please consider using your primary keys on your where statement rather a varchar field, as it'll improve speed when more complex queries. (eg. where user_id = 35 instead of where username = 'dodlo.rg' ).
Lastly, but quite important this code might be vulnerable to sql injections. You need to use prepared statements.
You have to convert this query into two parts
$sql1 = "UPDATE user SET username = $newName WHERE username = 'dodlo.rg'";
$sql2 = "SELECT * FROM user";

php pdo sql query Error : 1064 with LIKE

My PDO query is throwing an error
42000 1064 You have an error in your SQL syntax
$sql = "SELECT * FROM {$this->config->__get('table_medicine')} WHERE patient_id = ? AND medicine LIKE %?%";
$query = $this->dbh->prepare($sql);
$data = array($patient_id, $medicine);
$response = $query->execute($data) or die(implode(" ", $query->errorInfo()));
Can someone see what am I doing wrong?
The % need to be inside the string argument to LIKE. Either use CONCAT() in the SQL:
$sql = "SELECT * FROM {$this->config->__get('table_medicine')}
WHERE patient_id = ? AND medicine LIKE CONCAT('%', ?, '%')";
or do the concatenation in PHP:
$data = array($patient_id, '%'.$medicine.'%');

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

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

Syntax error but I don't see it? (PHP/MySQLi_Query)

So I have been working on different PHP scripts all day, so I don't know if it's just my eyes and I need a break or what: but I wrote a line to connect to MySQL database, and check if a username already exists. However I get error messages of course that are less than helpful (even when searched they don't seem to apply to what I am working on or just simply don't show up anything.
Error one (before I put in or die(mysqli_error($myCon)):
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/icangame/public_html/dev/php/userRegister.php on line 40
Error Two (AFTER I put in the or die statement):
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 '== `user`' at line 1
Code that this apples to (will post more if you want, it's a big file.):
$checktherow = mysqli_query($myCon, "SELECT * FROM users WHERE `username` == `$realUsername`") or die(mysqli_error($myCon));
if (mysqli_num_rows($checktherow) == 0)
{
mysqli_query($myCon, "INSERT INTO users (username, password, email)
VALUES ('$realUsername', '$realPassword', '$email')") or
die(mysqli_error($myCon));
}
Thanks, Tim
I think you need a break
replace
$checktherow = mysqli_query($myCon, "SELECT * FROM users WHERE `username` == `$realUsername`") or die(mysqli_error($myCon));
WITH
$checktherow = mysqli_query($myCon, "SELECT * FROM users WHERE `username` = `{$realUsername}`") or die(mysqli_error($myCon));
NOTE == in your query
It was mysql syntax error so $checktherow is returning false
The query is failing, so it assigns $checktherow a value of "false". When you run mysqli_num_rows($checktherow), it is getting a boolean value instead of a mysqli_result object that it expects
The problem is your query, you have "SELECT * FROM users WHERE username == $realUsername", but it should be "SELECT * FROM users WHERE username = $realUsername"
Dont use double equals when you want some specific from database , use it when you want to have comparison between values :
change this to :
username == $realUsername
this:
username = $realUsername
$checktherow = mysqli_query($myCon, "SELECT * FROM users WHERE `username` == `$realUsername`") or die(mysqli_error($myCon));
should be
$checktherow = mysqli_query($myCon, "SELECT * FROM users WHERE `username` ='".$realUsername."'") or die(mysqli_error($myCon));
Put a single = sign instead of == in your first line. Like this
$checktherow = mysqli_query($myCon, "SELECT * FROM users WHEREusername=$realUsername") or die(mysqli_error($myCon));

Categories