Cant insert string into mysql query - php

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

Related

How do I add a string at the end of user input in SQL/PHP

I have a SQL query that is based on user input.
However, in the table, theres a "-1" at the end of every word that you search for.
For example if you want to get the sql result of car, it's actually named car-1 in the database, but the user should only be able to search for car.
This is how its setup:
$sql = "SELECT * FROM that WHERE this = ?";
$stmt = $conn->prepare($sql);
$search_query = $_POST['this'];
$stmt->bind_param('s', $search_query);
$stmt->execute();
$result = $stmt->get_result();
What I want, is that the select query should be like:
$sql = "SELECT * FROM that WHERE this = ? + '-1'";
But ^^ doesn't work.
$sql = "SELECT * FROM test WHERE NAME='car' & -1";
test = that
NAME= table name
'car' = this
Why don't you just concat -1 to search_query :
$sql = "SELECT * FROM that WHERE this = ?";
$stmt = $conn->prepare($sql);
$search_query = $_POST['this'];
$stmt->bind_param('s', $search_query.'-1');
$stmt->execute();
$result = $stmt->get_result();
Using MySQL:
$sql = "SELECT * FROM that WHERE this = CONCAT(?, '-1')";
Using PHP:
$stmt->bind_param('s', $search_query . "-1");

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 PHP variables dynamically in MySQL statements

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?

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?

How to query a database with an array? WHERE = 'array()'

I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!
You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.
Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);

Categories