Query in PHP not working when using variables [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
Improve this question
This query works fine:
$query = "SELECT * from hired WHERE username = 'kaas' and dvd = 'dvd 2'";
But then I change it to this query:
$query = "SELECT * from hired WHERE username = " . $_SESSION['name'] . " AND dvd = " . $_POST['dvd'];
and it doesn't work, even though the values should be the same as the top query. It goes straight to my error message, 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 '2' at line 1
The dvd's are having names like 'dvd 1' 'dvd 2' 'dvd 3'. Why is it not working? Is there anything wrong in my query?
I tried to use the query with the data written down instead of using the session and post. It worked as I expected, and showed me an echo.

You are not wrapping your string values in quotes
You must use prepared statements for security reasons (SQL Injection and escaping invalid values
$query = "SELECT * from hired WHERE username = :name AND dvd = :dvd";
$statement = $pdo->prepare($query);
$statement->execute([':name' => $_SESSION['name'], ':dvd' => $_POST['dvd']]);
$result = $statement->fetchAll();

It needs to be
$query = "SELECT * from hired WHERE username = '" . $_SESSION['name'] . "'" . "AND dvd = '" . $_POST['dvd'] . "'";
I forgot to put a ' around them, so it would see it (for example) as 'username = Fal' instead of 'username = 'Fal'

You have to concatenate variables inside query properly. Try this it will work.
$query = "SELECT * from hired WHERE username = '" . $_SESSION['name'] . "' AND dvd = '".$_POST['dvd']."'";

Related

error in your SQL syntax; [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
hi i am getting this error though i tried to change the new to i am stil getting this problem can anyone tell me what should i do. I have completely changed the page also database but still same error.
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 ''calendar_admin' WHERE teacher_id='ipcst123' and password='a141c47927929bc2d1fb6'
at line 1
my code >
<?php
$username=$_POST['teacherId'];
$password=$_POST['password'];
$password=md5($password);
try {
$bdd = new PDO('mysql:host=localhost;dbname=XXX', 'XXX', 'XXX');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
$query ="SELECT * FROM 'calendar_admin' WHERE teacher_id="."'".$username."' and password="."'".$password."' ";
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
$res = $resultat->fetchAll(PDO::FETCH_ASSOC);
foreach($res as $result){
$pass=md5($password);
$user=$result["teacher_id"];
if ($pass==$result["password"]&& $username == $user ){
echo "login Success";
session_start();
$_SESSION['teacher_id'] = $username;
header('Location:/addEvents.php');
}else{
header('Location:/login.php');
//echo "Incorrect Password";
}
}
You should use backticks instead of single quotes :
$query ="SELECT * FROM `calendar_admin` WHERE teacher_id='".$username."' and `password`='".$password."' ";
or just remove them
$query ="SELECT * FROM calendar_admin WHERE teacher_id='".$username."' and `password`='".$password."' ";
And since you use PDO, you should bind parameters, but not concatenate them into the query:
$query ="SELECT * FROM calendar_admin WHERE teacher_id= :teacher and `password`= :password ";
$sth = $bdd->prepare($query);
$sth->bindParam(':teacher',$username);
$sth->bindParam(':password',$password);
$sth->execute();
$res = $sth->fetchAll(PDO::FETCH_ASSOC);
Around column and table names has to be backticks, not single quotes. O rnothing if the names aren't from reserved words (or spaces, or hyphens, or anything else that MySQL will scream about, #Fred -ii- in comments below):
`calendar_admin`
The full query:
$query ="SELECT *
FROM `calendar_admin`
WHERE teacher_id = '" . $username . "' AND
password = '" . $password . "'";
Don't forget to escape data from user inputs.
$query = "
SELECT *
FROM calendar_admin
WHERE teacher_id = '$username'
AND password = '$password';
";
Next, take a look at prepared statements

Correct way of passing a PHP $variable to MySQLI [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I am wondering about the safe or correct way to pass a $variable to a query. I am new to PHP thats why I am asking such beginner question. Here is the example one and two, which one is correct and safer because of symbols?
Example one:
//here is the line I am asking about. The $identification
$query = "SELECT * FROM `members` WHERE `username` = '$identification' LIMIT 1";
Example two:
//here is the line I am asking about. The $identification
$query = "SELECT * FROM `members` WHERE `username` = '" . $identification . "' LIMIT 1";
I don't need answers about PHP 4 or 5 or PDO. I just need to know what is correct:
This
'" . $identification . "'
Or this
'$identification'
I would recommend you to use PDO instead of the mysqli extension (works with php 5.1 and above)
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
How about
$query =
"SELECT * FROM `members` WHERE `username` = '" .
mysql_escape_string($identification) .
"' LIMIT 1";
http://php.net/manual/en/function.mysql-escape-string.php
However, mysql_escape_string is deprecated. If you can, you should use mysql_real_escape_string
http://php.net/manual/en/function.mysql-real-escape-string.php

Why PDO does not bind my params? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a query with some parameters that I bind with PDO. This is my code:
$sql = "SELECT altezza_pneumatici FROM tbl_catalogo_pneumatici "
. "WHERE sigla_produttore = :marca "
. "AND larghezza_pneumatici = :larghezza"
. "GROUP BY altezza_pneumatici "
. "ORDER BY altezza_pneumatici ASC";
$query = $DBobj->dbConn->prepare($sql);
$query->bindValue(':marca', $marca, PDO::PARAM_STR);
$query->bindValue(':larghezza', $larghezza, PDO::PARAM_STR);
$query->execute();
But it does not work. I have this error:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\Users\mydoc\Documents\pjct\web_gomme_new\class\class.Pneumatico.php on line 116
What is the problem? I printed both variables used in binding function, and they have correct values.
I can not say for sure if this is the problem, but there is an error in your query. (missing space).
$sql = "SELECT altezza_pneumatici FROM tbl_catalogo_pneumatici "
. "WHERE sigla_produttore = :marca "
. "AND larghezza_pneumatici = :larghezza[ ]"
. "GROUP BY altezza_pneumatici "
. "ORDER BY altezza_pneumatici ASC";
See the brackets behind :larghezza.
Your query will end up being "..AND larghezza_pneumatici = :larghezzaGROUP BY altezza_pneumatici...".
You do not need to break up the SQL query string.
$sql = "SELECT altezza_pneumatici FROM tbl_catalogo_pneumatici
WHERE sigla_produttore = :marca
AND larghezza_pneumatici = :larghezza
GROUP BY altezza_pneumatici
ORDER BY altezza_pneumatici ASC";
Is fine. Whitespace at end of each line. This should do the trick.

values from 2 arrays to mysql table php [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Well please help to correct syntax fo the following code. I have to select 2 values from one table and insert them in another table. one value is taking from PHP variable.this all needs to be done using Opencart model file
$this->db->query("UPDATE " . DB_PREFIX . "rate_cost SET rate_cost = " . $this->db->escape($data['rate_cost']) );
$sql = "SELECT DISTINCT competition_rate, customer_id FROM " . DB_PREFIX . "customer WHERE competition_rate NOT LIKE 0";
$query = $this->db->query($sql);
$rates = array();
$customer_ids = array();
foreach($query->row['competition_rate'] as $result){
$rates[] = $result * $data['name'];
}
foreach($query->row['customer_id'] as $result2){
$customer_ids[] = $result2;
}
$sums = $rates;
$ids = $customer_ids;;
$sql = ("INSERT INTO 'customer_transaction'(customer_id,amount) VALUES'".$ids.",".$sums"'");
}
I am getting the folowing error:
Parse error: syntax error, unexpected '"'"' (T_CONSTANT_ENCAPSED_STRING) in C:\xampp\htdocs\sport\admin\model\competition\newsletter.php on line 18
You have some syntax errors in your $sql query, the correct syntax for INSERT query is
INSERT INTO table (columns) VALUES ('values');
So youre missing paranthesis for your values and you dind't surround correctly with quotes. So change as follow
VALUES ('".$ids."','".$sums"')");
So the complete query will look like that
("INSERT INTO 'customer_transaction'(customer_id,amount) VALUES ('".$ids."','".$sums"')");

php mysqli escape string error in sql syntax [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to escape fields posted from a form. I can successfully insert into the SQL database by commenting out the code that escapes the string.
The error received is:
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 '\"test\",\"0123456789\",\"test#test.com\",\"1\",\"1\",\"fgsdfdfndfndfndfndfndfn\' at line 1
Here is the code I am using:
$Name= $_POST['fullname'];
$Phone = $_POST['phone'];
$email = $_POST['email'];
$inBuilding = $_POST['inbuilding'];
$floor = $_POST['floor'];
$inRoom = $_POST['inroom'];
$majorDescription = $_POST['majorcategory'];
$description = $_POST['desc'];
$query = "INSERT INTO `problem`.`reports` (`Name`, `PhoneNumber`, `EmailAddress`, `inBuilding`, `inRoom`, `Description`, `MajorDescription`) VALUES (";
$query .= '"' . $Name. '","' . $Phone . '","' . $email . '","' . $inBuilding . '","' . $inRoom . '","' . $description . '","' . $majorDescription . '");';
$query = mysqli_real_escape_string($connect, $query);
I have also tried:
$query = mysqli_escape_string($connect, $query);
with the same error.
According to other examples on stack overflow I changed the INSERT INTO code to the following:
$query = "INSERT INTO `problem`.`reports` (Name, PhoneNumber, EmailAddress, inBuilding, inRoom, Description, MajorDescription) VALUES ('$Name', '$Phone', '$email', '$inBuilding', '$inRoom', '$description', '$majorDescription')");
This code gave server 500 error.
MySQL is fully updated.
Any assistance appreciated!
MikeW's solution worked. Also realized I was trying to escape the string before I had opened the database making mysqli_real_escape_string return null. Connecting to the database first, ($connect= new connect("server","user","password");) solved this problem. Hopefully this will help anyone else with the same problems.
You should be using single quotes, not double quotes. Also, mysqli_real_escape_string() should be called on each variable, not on the query as a whole. You should get something like this:
$Name= mysqli_real_escape_string($connect, $_POST['fullname']);
// more variables, similarly escaped.
$query = "INSERT INTO `problem`.`reports` (`Name`, `PhoneNumber`, `EmailAddress`, `inBuilding`, `inRoom`, `Description`, `MajorDescription`) VALUES (";
$query .= "'$Name','$Phone','$email','$inBuilding','$inRoom','$description','$majorDescription')";
However, for this sort of query you should consider using prepared statements.
I'm not sure if MySQL works with double-quotes. You should use single-quotes. But the more glaring issue is that you need to call mysqli_real_escape_string() on every variable, not the entire query string.
To simplify the problem, say your query was as follows:
$query = "INSERT INTO tbl (Name) VALUES ('". $_POST['name'] ."')";
$query = mysqli_real_escape_string($connect, $query);
And then say I pass in a value, Michael O'Connor. What does your query become?
INSERT INTO tbl (Name) VALUES (\'Michael O\'Connor\')
Notice that not only did the ' in the actual name get escaped, but the quotes to surround that name also got escaped. If you called mysqli_real_escape_string() on the entire compiled query string, it has no way to distinguish a ' in the value vs. the ones that are supposed to surround the value.

Categories