Using PHP variables dynamically in MySQL statements - php

I am trying to execute the query below.
$condition = "WHERE emp_id = '$emp_id'";
$myquery = "SELECT * FROM emp_table".$condition;
I expect my query to be like this, but dynamically:
$myquery = "SELECT * FROM emp_table WHERE emp_id = '$emp_id'";
Is there anyway to make SQL statements dynamically through variables in php..?

It should be
$condition = "WHERE emp_id = '$emp_id'";
$myquery = "SELECT * FROM emp_table ".$condition;
you forgot to put $ on myquery

You should never build queries dynamically like that. Correct way to do it is to use prepared statements.
In your case it'll be like that
$statement = $pdo->prepare("SELECT * FROM emp_table WHERE emp_id = :emp_id");
$statement->execute(array(
':emp_id' => $emp_id
));
$rows = $statements->fetchAll(PDO::FETCH_ASSOC);

Have you tried this? -
$condition = "WHERE emp_id = '" . $emp_id . "'";
$myquery = "SELECT * FROM emp_table " . $condition;
PHP does not expand variables within single-quote strings.
echo "$name"; //works
echo '$name'; //does not work
Take a look at this: Single quotes or double quotes for variable concatenation?

Related

Cant insert string into mysql query

I'm trying to make a login page in PHP, and I'm trying to construct the query here:
$q = 'SELECT * FROM users WHERE userid="'+$username+'"';
When I echo it out with
echo $q
I get 0. When I do
$q = 'SELECT * FROM users WHERE userid="'+"test"+'"';
I get 0. When I do
$q = 'SELECT * FROM users WHERE userid="michael"';
I get my expected result of the string being printed out
Use a . for concatenation, also don't forget to clean the data to prevent mysql injection.
$user_id = 'test';
$q = 'SELECT * FROM users WHERE userid="' . $user_id . '"';
Try using a PDO Prepared statement to protect yourself from SQL injection.
$q = 'SELECT * FROM users WHERE userid = ?';
$stmt = $dbh->prepare($q);
if ($stmt->execute(array($username))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
http://php.net/manual/en/pdo.prepared-statements.php
you can use .
$user_id = 'michael';
$q = 'SELECT * FROM users WHERE userid="'.$user_id.'"';
or use double quotes for the expression and use single quotes for the variables
$user_id = 'michael';
$q = "SELECT * FROM users WHERE userid='$user_id'";
im Believe the second option is smallest and easiest to remember

To get two values as input in php

In my below php code the student rollno and name is got as input and the student address and mark will be displayed based on it. But the code works only if i give only 1 input.
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$rollno = $_GET['rollno'];
$name = $_GET['name'];
require_once('dbConnect.php');
$sql = "SELECT * FROM colleges WHERE rollno='".$rollno."'" and name='".$name."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"address"=>$res['address'],
"marks"=>$res['marks']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
replace $sql = "SELECT * FROM colleges WHERE rollno='".$rollno."'" and name='".$name."'";
To
"SELECT * FROM colleges WHERE rollno='".$rollno."' and name='".$name."'";
$sql = "SELECT * FROM colleges WHERE rollno='".$rollno."'" and name='".$name."'";
Corrected :
$sql = "SELECT * FROM colleges WHERE rollno='".$rollno."' and name='".$name."'";
But for better you should use prepared statements
Example
$link = mysqli_connect("localhost", "my_user", "my_password", "db_name");
$query = "SELECT * FROM colleges WHERE rollno=? AND name=?";
$params = array($rollno,$name);
mysqli_prepared_query($link,$query,"ss",$params)
Check and make sure the line $sql query is correct in your code because it is incorrect in your question.
$sql = "SELECT * FROM colleges WHERE rollno='".$rollno."'" and name='".$name."'";
Should be
$sql = "SELECT * FROM colleges WHERE rollno='" . $rollno . "' and name='" . $name ."'";
Or use single quotes for improved performance as:
$sql = 'SELECT * FROM colleges WHERE rollno = "' . $rollno .'" and name= "' . $name ."';
Secondly, what's the data type of your$rollno, if its not string then consider removing the single quotes surrounding it.
Thirdly, make sure both columns rollno and name have variables at all time, with the correct query else you all get a Null result.
Finally, I strongly suggest you use a pdo and its prepared statement next time.

Using SQL LIKE with variable PHP

I can't use the SQL LIKE with a variable
$sql = "SELECT * FROM chat WHERE name LIKE 'Motherboard' "; //This works
But if a use a variable it doesn't work:
$sql = "SELECT * FROM chat WHERE name LIKE '%'+$variable+'%' ";
//or
$sql = "SELECT * FROM chat WHERE name LIKE '$variable' ";
How can I fix it?
In PHP you concatenate strings with a dot .
$sql = "SELECT * FROM chat WHERE name LIKE '" . $variable . "' ";
You also can use variables within double quotes:
$sql = "SELECT * FROM chat WHERE name LIKE '$variable' ";
or
$sql = "SELECT * FROM chat WHERE name LIKE '{$variable}' ";
Keep in mind that double quotes work slower then single.
In your case it would be
$sql = "SELECT * FROM chat WHERE name LIKE '%{$variable}%' ";

Short Code for PHP string with variable

I have a query string that contains a variable like this
$field_name = 'features';
$value = '5';
$query = "SELECT * FROM Table WHERE $field_name\_tid = '$value'";
My goal is to print out the $query like this SELECT * FROM Table WHERE features_tid = '5';
I put \_ there hoping it would work as escape character, but it didn't work. Is there any way to achieve this without use methods like ". $field_name ." and modifying original variable value?
yes:
$query = "SELECT * FROM Table WHERE {$field_name}_tid = '$value'";
You can use:
$query = "SELECT * FROM Table WHERE {$field_name}_tid = '$value'";

Simple mysql query not working

I have this very simple function:
function getCatName($id){
$sql = "SELECT * FROM biznet_category WHERE ID ='".$id."';";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$name = $row["Name"];
return $name;
}
So with this function I should be able to get the category name, but it doesn't work with the parameter. If I put 8 or 9, the categoryname is displayed correctly.
The id is also passed on like it should, when I print it out, it shows 8 or 9.
I know the solution is quite simple, I just don't see it.
To fix remove the quotes and check the column name for case id or ID. Since the query string is in double quotes you don't have to use the . join
$sql = "SELECT * FROM biznet_category WHERE ID = $id";
You can use curly brackets which I find easier to read
$sql = "SELECT * FROM biznet_category WHERE ID = {$id}";
If you were querying a string rather than an integer you can simply do
$sql = "SELECT * FROM biznet_category WHERE ID = '{$id}'";
$sql = "SELECT * FROM biznet_category WHERE ID ='".$id."';";
To
$sql = "SELECT * FROM biznet_category WHERE ID = ".$id;
Try this
$sql = "SELECT * FROM biznet_category WHERE ID = ".$id;
Is the column name ID spelt correctly?

Categories