Unknown column 'AG' in 'where clause - php

I'm getting this error the error(title) on such a simple query:
function getBranch($BranchID){
$query = "SELECT Branch FROM Branches WHERE BranchID = {$BranchID}";
$r = mysql_query($query);
if (!$r) echo "Failed Query: " . mysql_error();
else return mysql_result($r, 0);
}
I know the mysql_ functions are being deprecated and I know the Column 'Branches' does exist. The var $BranchID is 'AG' when called and I've checked, that is a valid value.

You should not be using the deprecated mysql_* functions. It's much better to use PDO and parameterized queries.
The specific problem with your query is that you are missing quotes around your string value:
$query = "SELECT Branch FROM Branches WHERE BranchID = '$BranchID'";
You should also ensure that you escape the value correctly with mysql_real_escape_string.
$query = "SELECT Branch FROM Branches WHERE BranchID = '" .
mysql_real_escape_string($BranchID) . "'";
Related
How can I prevent SQL injection in PHP?

Related

How to insert a PHP variable into an SQL query

I have an SQL query
qry1 =
"SELECT DISTINCT (forename + ' ' + surname) AS fullname
FROM users
ORDER BY fullname ASC";
This gets forename and surname from a table called users and concatenates them together, putting a space in the middle, and puts in ascending order.
I then put this into an array and loop through it to use in a select drop-down list.
This works, however, what I now want to do is compare the fullname with a column called username in another table called users.
I'm struggling with how to write the query though. So far I have...
$qry2
"SELECT username
FROM users
WHERE (forename + ' ' + surname) AS fullname
=" . $_POST['Visiting'];
Any advice on to what I am doing wrong?
Rather CONCAT the two columns together. Also remember to escape any variables before adding them to your query.
$qry2 =
"SELECT username AS fullname
FROM users
WHERE CONCAT(forename, ' ', surname)
='" . mysqli_real_escape_string($connection, $_POST['Visiting']) . "'";
Where $connection is your current db connection
I'm not sure that the use of the declared word 'AS' after 'WHERE' is correct in principle.
if you use MySQL, query should look like this:
SELECT [columns]
FROM [tables] [AS declareTableName]
WHERE [condition]
GROUP BY [declares|columns]
SORT BY [declares|columns]
But, i think your problem not in the query. Concatenating names in the query is incorrect. You must separate string with names in Back-end and than use it in query:
$names = explode(' ', $_POST['Visiting']);
This might work, assuming you use PDO:
$qry2 = "SELECT username FROM users
WHERE CONCAT(forename, ' ', surname) = '" . $conn->quote($_POST['Visiting']) . "'";
...but you should have a look at the possible vulnerabilities through SQL injections.
Without knowing which library you use for connecting to the MySQL database, it's impossible to give proper advise about which method you should use for escaping the user's input. quote is the PDO method for escaping, real-escape-string is the equivalent for MySQLi
You should really refer to using PDO.
When using PDO you can bind parameters to specified parts of your query. PDO also has built-in SQL-injection prevention, which is a great security measure that you won't have to deal with yourself. I hope this answers your question. See my example below.
Example:
// Create a new PDO object holding the connection details
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Create a SQL query
$query = "SELECT username FROM users WHERE (forename + ' ' + surname) AS fullname = :visiting;";
// Prepare a PDO Statement with the query
$sth = $pdo->prepare($query);
// Create parameters to pass to the statement
$params = [
':visiting' => $_POST['Visiting']
]
// Execute the statement and pass the parameters
$sth->execute($params);
// Return all results
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
If you have any other questions about PDO, please refer to the following:
Official PDO documentation:
http://php.net/manual/en/book.pdo.php
Documentation on how to bind variables:
http://php.net/manual/en/pdostatement.bindparam.php
You can use this construction (without "AS fullname" and with apostrophes around variable):
$qry2 "SELECT username FROM users WHERE (forename + ' ' + surname) = '" . $_POST['Visiting'] . "'";
But for better security (SQL injection) You should use the escaping of variable. For example this construction, if You use MySQL database:
$qry2 "SELECT username FROM users WHERE (forename + ' ' + surname) = '" . mysql_real_escape_string($_POST['Visiting']) . "'";

mysql_query() returns something strange

I want to select one field (MessageCounter) from my database. Its type is int(11). And I want to increase it.
Here's how I try to select it:
$q = "SELECT MessageCounter FROM " . TBL_USERS . " WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
then I try to add 1 to it:
$messagecount = $result + 1;
$field = "MessageCounter";
$q = "UPDATE " . TBL_USERS . " SET " . $field . " = '$messagecount' WHERE username = '$username'";
return mysql_query($q, $this->connection);
And in the database it updates to 19. If I add other number instead of 1, say 3, I get 21. So the $result is somehow equal to 18.
HOWEVER, if I try to update the database with the same unchanged result - it updates the field to 0.
Does anyone have any idea what is happening?
You cannot add 1 to $result - first you need to fetch the value out of it:
$row = mysql_fetch_row($result);
$messagecount = $row[0] + 1;`
BTW - at this stage of learning, you should abandon the deprecated mysql_ functions and switch to mysqli or PDO instead. Do it right now.
mysql_query() returns a Resource and not a normal variable on which you can perform addition operation.
and as n-dru suggested you should switch to PDO or mysqli coz mysql extension is deprecated in PHP 5.5.0 and it's removed from PHP 7.0.0.
read here

Parameterised IN Clause in prepared statement using MySql,PHP and ADODB

I am writing some SQL and using AdoDb to connect to my database and run the queries and so on. I am using parametrized queries and have run into a snag.
Is their a way to pass an array of values to an in_clause in AdoDb/MySql for parametrization.
My problem is that if I pass a prepared string as the parameter i.e. 'test','test2','test3' it does not work as the library or database auto escapes it and adds external quotes at the start and end so all the internal quotes are then auto escaped thus the query returns nothing as it looks for '\'test\',\'test2\',\'test3\'' as opposed to what I fed it.
UPDATED WITH ANOTHER POSSIBLE METHOD TO ACCOMPLISH THIS
<?php
$in_clause = implode(",", $first_names);
$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
FIND_IN_SET(mytable_fname," . $DB->Param('first_names') . ")"
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,array($in_clause));
?>
I would do it this way (as I was googling for a while and google came up with nothing useful):
$count = count($first_names);
$in_params = trim(str_repeat('?, ', $count), ', ');
$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
mytable_fname IN ({$in_params});";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt, $first_names);
This should do it...
First a few tips:
Please read carefully the AdoDB documentation on prepared statements.
Never include ; in SQL query strings.
You can try something like this:
$question_marks = substr(str_repeat('?,', count($first_names)), 0, -1);
$query = "SELECT mytable_id_pk FROM mytable WHERE mytable_fname IN (" . $question_marks . ")";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,$first_names);
WARNING: I haven't tested this (not having a mySQL installation here).

Invalid MySQL Query when passing in value from external select box

I have two files in use. The first is a front end select box with a list of dynamically populated char/text values that uses POST to send the selected value to a back end file. This back end file assigns this value to a variable and that variable is then used in the following query:
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName =".$hosname;
However, I keep getting the Invalid Query message I have set in my or die(); and I have no idea why. The full section of php code on the backend file is as follows:
$conn = mysqli_connect("localhost", "root", "") or die ("No connection");
mysqli_select_db($conn, "hospitaldb") or die("db will not open");
$hosname=$_POST['valuelist'];
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName =".$hosname;
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'><tr><th>mDoctorName</th><th>Speciality</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</table>";
mysqli_close($conn);
Note: I have checked that the value from the select box is being passed in using print and it is. Any help would be greatly appreciated.
*I am only testing this locally but thanks to all who recommended mysql_real_escape_string() to protect against injections.*
It looks like you're not wrapping the value in quotes, so the query is malformed. My PHP is rusty, excuse me if there is a syntax error in my example, below:
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName ='".$hosname ."';";
However, the string concatenation leaves you open to SQL Injection (http://en.wikipedia.org/wiki/SQL_injection). Consider using prepared statements http://php.net/manual/en/pdo.prepare.php
The resulting SQL query you want would be something like;
SELECT DoctorName, Speciality FROM hospital WHERE HospitalName = 'MyHospital'
In other words, you need to add quotes to your query creation;
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName = '".$hosname."'";
You should really also escape the hospital name using mysql_real_escape_string() before just inserting it into a query.
Actually, your error is you need to surround your variable in single quotes like:
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName ='".$hosname."'";
I'm assuming $hosname is a string. Your query is failing because you haven't quoted it.
$query = "SELECT DoctorName, Speciality FROM hospital
WHERE HospitalName = '" . mysql_real_escape_string($hosname) . "'";
Note I added mysql_real_escape_string as well as the quotes to protect from SQL Injection attacks. You should read and learn about SQL Injection attacks because your code is vulnerable to them. Also consider using PDO which helps take care of these things for you.
Use ' (quotes) around your .$hosname variable name.

Am I using mysql_real_escape_string right?

Is this the right way to use mysql_real_escape_string? I was using $GET but a friend told me to make it safer with real_escape_string:
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = $id") or die("err0r");
if(!$result) mysql_real_escape_string($id); {
No, you normally use mysql_real_escape_string to prepare variables for use in a query, but in your case:
you already use intval;
you use it in the wrong place.
You don't need it in your example.
No. That is entirely wrong, and I can't quite understand what you're intending the call to do.
The purpose of mysql_real_escape_string is to avoid SQL injection, which is one of the biggest security risks in a website. It stops your users giving input that manipulates the SQL in evil ways. For instance:
$sql = "SELECT FROM users WHERE username = '" . $_GET['username'] . "'";
If I put lonesomeday' or 'a' = 'a into $_GET['username'], your query becomes
SELECT FROM users WHERE username = 'lonesomeday' or 'a' = 'a'
and obviously arbitrary SQL could then be executed. mysql_real_escape_string escapes unsafe characters (such as ' in that example), so that they can't be used in this way.
$sql = "SELECT FROM users WHERE username = '" . mysql_real_escape_string($_GET['username']) . "'";
// SELECT FROM users WHERE username = 'lonesomeday\' or \'a\' = \'a'
The quotes are now escaped. so the query can't be manipulated into doing evil things.
With all that said, in this case, intval does all you need. It also ensures that nothing that is not an integer can be in $id, so your code is safe here from SQL injection.
NO, you need to escape before quering
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = '" . mysql_real_escape_string($id) . "'") or die("err0r");
if(!$result) {
}
Use:
$query = sprintf("SELECT *
FROM products
WHERE id = %d",
intval($_GET['id']));
$result = mysql_query($query) or die("err0r");
You use mysql_real_escape_string before the value is used in the query, otherwise you're not handling the SQL injection attack.
you want to escape it before you stick it in a query (Before it interacts with DB so you don't get injections).
// check if your $_GET is not empty otherwise you
// will run into "undefined variable"
if(!empty($_GET['id'])){
$id = intval($_GET['id']);
// to simplify you can escape here,
// or to be a bit more complex, you can escape in the query line.
$id = mysql_real_escape_string($id);
$result = mysql_query("SELECT *
FROM products
WHERE id = '$id'") or die("err0r");
}
else
print 'No ID';

Categories