Using variables in SELECT statement for column name - php

I am using the method below to get values from the database (from the "$column" column) and it is working as intended but i would like to know the correct way to implement the "$column" variable that is added in the SELECT statement, so as to be as safe as possible from injection (either by preparing with a ?-type placeholder or by properly escaping). What would be the most modern and safe approach?
NOTE: $qry->bind_param("ss",$column,$rowName); with 2 ? placeholders doesn't work.
$column = $_POST['column'];
$rowName = $_POST['rowName'];
$qry = $connection->prepare("SELECT $column FROM database_name WHERE row_name=?");
$qry->bind_param("s",$rowName);
$qry->execute();
$result = $qry->get_result();

$column = $_POST['column'];
$rowName = $_POST['rowName'];
$qry = $connection->prepare("SELECT * FROM database_name WHERE row_name=?");
$qry->bind_param("s",$rowName);
$qry->execute();
$result = $qry->get_result();
$value = $result[$column];

Related

MyPHP webcall using 2 different values seperated by the & sign

I am in need of some help, please? I can successfully do a MySQL query using:
IP_Address/fund_list.php?Id_Number=555666
With this below:
$ID = $_GET['Id_Number'];
$sql = "SELECT * FROM fund_list WHERE Number = ".$ID;
Now I want to use 2 different things in my web call. Like:
IP_Address/fund_list.php?Id_Number=555666&Name=Billy
But I don't know how to write the 'get' line below.
$ID = $_GET['Id_Number'] & $Name = $_GET['Name']; <-- Does not work
I would think the SQL select statement would be:
$sql = "SELECT * FROM fund_list WHERE TheNumber = .$ID AND TheName = .$Name";
All the things I look up online, the syntax is overly confusing, I can't dissect it and make something work. Thank you.
To start with you should really be preparing your statements, passing data directly from a query string into a SQL query is really dangerous. You should also avoid using * in your SELECTs if you insist on not preparing them.
Your issue in this case is you need '' around TheName =
$sql = "SELECT * FROM fund_list WHERE TheNumber = {$ID} AND TheName = '{$Name}'";
Regardless, what you should be doing is this:
$sql = "SELECT Param1, Param2 FROM fund_list WHERE TheNumber = ? AND TheName = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $ID, $Name);
$stmt->execute();
$stmt->bind_result($param1, $param2);
while($stmt->fetch()) {
//Your code
}
That code prevents SQL injection attacks, and a number of other potential issues you can create not using PDO or mysqli prepared statements.
Edit per request:
$ID = $_GET['Id_Number'];
$Name = $_GET['Name'];
$sql = "SELECT * FROM fund_list WHERE TheNumber = {$ID} AND TheName = '{$Name}'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
//your code
}
You need '' when comparing string parameters in SQL.
Have you tried doing this? This always works to me
$ID = $_GET['Id_Number'];
$Name = $_GET['Name'];

Do i use PHP while loop or SQL group_concat

Both codes does the same Job, But which one is better to use and when to use?
PHP method
$names = [];
$Query = "SELECT DISTINCT name FROM names";
$stmt = $conn->prepare($Query);
$stmt->execute();
while ($name = $stmt->fetch()) {
$names[] = $name['epic'];
}
$names = implode(',', $names);
SQL method
$Query = "SELECT GROUP_CONCAT(DISTINCT name) AS names FROM names";
$stmt = $conn->prepare($Query);
$stmt->execute();
$row = $stmt->fetch();
$names = $row['names'];
It depends. GROUP_CONCAT() has the limit which is imposed by group_concat_max_len system option, and its length is 1024 by default (more info).
Also, it will concatenate non-null values, which you may want to handle in a different way, rather than just ignoring them.

Unable to concatenate sql in pdo statement [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I currently have a Get varible
$name = $_GET['user'];
and I am trying to add it to my sql statement like so:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
and run
$result = $pdo -> query($sql);
I get an invalid column name. But that doesn't make sense because if I manually put the request like so
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
I get the column data, just not when I enter it as a get variable. What am I doing wrong. I am relatively new to pdo.
Update:
Now I have the following:
$name = $_GET['user'];
and
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
but I am getting
> 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 ':name' at line
> 1
For your query with the variable to work like the one without the variable, you need to put quotes around the variable, so change your query to this:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
However, this is vulnerable to SQL injection, so what you really want is to use a placeholder, like this:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
And then prepare it as you have:
$result = $pdo->prepare( $sql );
Next, bind the parameter:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
And lastly, execute it:
$result->execute();
I find this best for my taste while preventing SQL injection:
Edit: As pointed out by #YourCommonSense you should use a safe connection as per these guidelines
// $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = 'SELECT * FROM uc_users WHERE user_name = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
// perhaps you'll need these as well
$count = $result->num_rows;
$row = $result->fetch_assoc();
/* you can also use it for multiple rows results like this
while ($row = $result->fetch_assoc()) {
// code here...
} */
BTW, if you had more parameters e.g.
$sql = 'SELECT * FROM table WHERE id_user = ? AND date = ? AND location = ?'
where first ? is integer and second ? and third ? are string/date/... you would bind them with
$stmt->bind_param('iss', $id_user, $date, $location);
/*
* i - corresponding variable has type integer
* d - corresponding variable has type double
* s - corresponding variable has type string
* b - corresponding variable is a blob and will be sent in packets
*/
Source: php.net
EDIT:
Beware! You cannot concatenate $variables inside bind_param
Instead you concatenate before:
$full_name = $family_name . ' ' . $given_name;
$stmt->bind_param('s', $full_name);
Try this .You didn't put sigle quote against variable.
$sql = "SELECT * FROM uc_users WHERE user_name = '". $name."'";
Note: Try to use Binding method.This is not valid way of fetching data.
$sql = "SELECT * FROM 'uc_users' WHERE user_name = '". $name."' ";

PHP and MySQL Select a Single Value [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I'd like to know how to select a single value from my MySQL table. The table includes columns username and id amongst others (id is auto-increment and username is unique). Given the username, I want to set a session variable $_SESSION['myid'] equal to the value in the id column that corresponds to the given username. Here's the code that I've already tried:
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$_SESSION['myid'] = $value;
So far I'm getting:
Catchable fatal error: Object of class stdClass could not be converted to string.
Casting $value to type string does not fix the problem.
Don't use quotation in a field name or table name inside the query.
After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)
The mysql_* functions are deprecated and unsafe. The code in your question in vulnerable to injection attacks. It is highly recommended that you use the PDO extension instead, like so:
session_start();
$query = "SELECT 'id' FROM Users WHERE username = :name LIMIT 1";
$statement = $PDO->prepare($query);
$params = array(
'name' => $_GET["username"]
);
$statement->execute($params);
$user_data = $statement->fetch();
$_SESSION['myid'] = $user_data['id'];
Where $PDO is your PDO object variable. See https://www.php.net/pdo_mysql for more information about PHP and PDO.
For extra help:
Here's a jumpstart on how to connect to your database using PDO:
$database_username = "YOUR_USERNAME";
$database_password = "YOUR_PASSWORD";
$database_info = "mysql:host=localhost;dbname=YOUR_DATABASE_NAME";
try
{
$PDO = new PDO($database_info, $database_username, $database_password);
}
catch(PDOException $e)
{
// Handle error here
}
You do this by using mysqli_fetch_field method.
session_start();
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' limit 1";
$result = mysqli_query($link, $sql);
if ($result !== false) {
$value = mysqli_fetch_field($result);
$_SESSION['myid'] = $value;
}
Note: you can do that by using mysql_fetch_field() method as well, but it will be deprecated in php v5.5
mysql_* extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.
PDO
The simpler option is PDO which has a neat helper function fetchColumn():
$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();
Proper PDO tutorial
MySQLi
You can do the same with MySQLi, but it is more complicated:
$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;
fetch_assoc() could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.
Since PHP 8.1 you can also use fetch_column()
$stmt->execute();
$value = $stmt->get_result()->fetch_column();
Try this
$value = mysql_result($result, 0);
When you use mysql_fetch_object, you get an object (of class stdClass) with all fields for the row inside of it.
Use mysql_fetch_field instead of mysql_fetch_object, that will give you the first field of the result set (id in your case). The docs are here
It is quite evident that there is only a single id corresponding to a single username because username is unique.
But the actual problem lies in the query itself-
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
O/P
+----+
| id |
+----+
| id |
+----+
i.e. 'id' actually is treated as a string not as the id attribute.
Correct synatx:
$sql = "SELECT `id` FROM Users WHERE username='$name'";
i.e. use grave accent(`) instead of single quote(').
or
$sql = "SELECT id FROM Users WHERE username='$name'";
Complete code
session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;
try this
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
$_SESSION['myid'] = $row['id'];
}

Possible to have PHP MYSQL query ignore empty variable in WHERE clause?

Not sure how I can do this. Basically I have variables that are populated with a combobox and then passed on to form the filters for a MQSQL query via the where clause. What I need to do is allow the combo box to be left empty by the user and then have that variable ignored in the where clause. Is this possible?
i.e., from this code. Assume that the combobox that populates $value1 is left empty, is there any way to have this ignored and only the 2nd filter applied.
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND location = '$value1' AND english_name = $value2 ";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Thanks for any help.
C
Use
$where = "WHERE user_id = '$username'";
if(!empty($value1)){
$where .= "and location = '$value1'";
}
if(!empty($value2 )){
$where .= "and english_name= '$value2 '";
}
$query = "SELECT * FROM moth_sightings $where";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Several other answers mention the risk of SQL injection, and a couple explicitly mention using prepared statements, but none of them explicitly show how you might do that, which might be a big ask for a beginner.
My current preferred method of solving this problem uses a MySQL "IF" statement to check whether the parameter in question is null/empty/0 (depending on type). If it is empty, then it compares the field value against itself ( WHERE field1=field1 always returns true). If the parameter is not empty/null/zero, the field value is compared against the parameter.
So here's an example using MySQLi prepared statements (assuming $mysqli is an already-instantiated mysqli object):
$sql = "SELECT *
FROM moth_sightings
WHERE user_id = ?
AND location = IF(? = '', location, ?)
AND english_name = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ssss', $username, $value1, $value1, $value2);
$stmt->execute();
(I'm assuming that $value2 is a string based on the field name, despite the lack of quotes in OP's example SQL.)
There is no way in MySQLi to bind the same parameter to multiple placeholders within the statement, so we have to explicitly bind $value1 twice. The advantage that MySQLi has in this case is the explicit typing of the parameter - if we pass in $value1 as a string, we know that we need to compare it against the empty string ''. If $value1 were an integer value, we could explicitly declare that like so:
$stmt->bind_param('siis', $username, $value1, $value1, $value2);
and compare it against 0 instead.
Here is a PDO example using named parameters, because I think they result in much more readable code with less counting:
$sql = "SELECT *
FROM moth_sightings
WHERE user_id = :user_id
AND location = IF(:location_id = '', location, :location_id)
AND english_name = :name";
$stmt = $pdo->prepare($sql);
$params = [
':user_id' => $username,
':location_id' => $value1,
':name' => $value2
];
$stmt->execute($params);
Note that with PDO named parameters, we can refer to :location_id multiple times in the query while only having to bind it once.
if ( isset($value1) )
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND location = '$value1' AND english_name = $value2 ";
else
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND english_name = $value2 ";
But, you can also make a function to return the query based on the inputs you have.
And also don't forget to escape your $values before generating the query.
1.) don't use the simply mysql php extension, use either the advanced mysqli extension or the much safer PDO / MDB2 wrappers.
2.) don't specify the full statement like that (apart from that you dont even encode and escape the values given...). Instead use something like this:
sprintf("SELECT * FROM moth_sightings WHERE 1=1 AND %s", ...);
Then fill that raw query using an array holding all values you actually get from your form:
$clause=array(
'user_id="'.$username.'"',
'location="'.$value1.'"',
'english_name="'.$value2.'"'
);
You can manipulate this array in any way, for example testing for empty values or whatever. Now just implode the array to complete the raw question from above:
sprintf("SELECT * FROM moth_sightings WHERE 1=1 AND %s",
implode(' AND ', $clause) );
Big advantage: even if the clause array is completely empty the query syntax is valid.
First, please read about SQL Injections.
Second, $r = mysql_numrows($result) should be $r = mysql_num_rows($result);
You can use IF in MySQL, something like this:
SELECT * FROM moth_sightings WHERE user_id = '$username' AND IF('$value1'!='',location = '$value1',1) AND IF('$value2'!='',english_name = '$value2',1); -- BUT PLEASE READ ABOUT SQL Injections. Your code is not safe.
Sure,
$sql = "";
if(!empty($value1))
$sql = "AND location = '{$value1}' ";
if(!empty($value2))
$sql .= "AND english_name = '{$value2}'";
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' {$sql} ";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Be aware of sql injection and deprecation of mysql_*, use mysqli or PDO instead
I thought of two other ways to solve this:
SELECT * FROM moth_sightings
WHERE
user_id = '$username'
AND location = '%$value1%'
AND english_name = $value2 ";
This will return results only for this user_id, where the location field contains $value1. If $value1 is empty, this will still return all rows for this user_id, blank or not.
OR
SELECT * FROM moth_sightings
WHERE
user_id = '$username'
AND (location = '$value1' OR location IS NULL OR location = '')
AND english_name = $value2 ";
This will give you all rows for this user_id that have $value1 for location or have blank values.

Categories