How should I write SQL query that contains LIKE in PHP? - php

I want to make a query that ends in LIKE value%, but for some reason, there is an error with it.
$_GET['letter'] contains the starting letter that I want to use in my query.
For example if its 'a', my query will be ...WHERE name LIKE 'a%'.
My code:
$sql = sprintf("SELECT id, name, username, email FROM users WHERE name LIKE '" . ($_GET['letter']) . "%'");
The error I get is: PHP Warning: sprintf(): Too few arguments
And then of course: PHP Warning: mysqli::query(): Empty query
Thanks in advance.

Don't even consider taking this route. Use prepared statements with PDO or mysqli instead.
if(isset($_GET['letter']) && strlen($_GET['letter']) > 0) {
$letter = $_GET['letter'] . '%';
$sql = "SELECT id, name, username, email FROM users WHERE name LIKE ?";
$query = $con->prepare($sql);
$query->bind_param('s', $letter);
$query->execute();
$query->bind_result($id, $name, $username, $email);
while($query->fetch()) {
echo $id . '<br/>';
// and others
}
// alternate version with mysqlnd installed
// $results = $query->get_result();
// while($row = $results->fetch_assoc()) {
// echo $row['id'];
// }
} else {
echo 'please provide for search value';
}

Related

Full text search with mysql php

I am trying to make a search key feature. But I am not getting any result with the following query.
public function SearchKey($key,$userid)
{
$key = mysqli_real_escape_string($this->db, $key);
$userid = mysqli_real_escape_string($this->db, $userid);
$query = mysqli_query($this->db,"SELECT * FROM posts WHERE
MATCH(theKey) AGAINST('$key' IN NATURAL LANGUAGE MODE)
AND uid = '$userid' ORDER BY sgq_id LIMIT 5") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($query)) {
$data[]=$row;
}
if(!empty($data)) {
return $data;
}
}
Then fetch,
$search = $Data->SearchKey($key, $userid);
if($search){
foreach($search as $data){
echo $data['theKey'];
}
}
For example if I search OK005 then I can not get any results. I tried Full-text Search functions https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
Anyone can help me here, what I am missing ?
You're using single quotes to pass your variables. These will not be expanded in your query. You're better off using a prepared statement, and use parameter/value bindings to pass the variables. This will also solve the problem of SQL injection that your code appears to be vulnerable to.
You can try something like:
// Replace comment with appropriate connection data.
$pdo = new PDO(/* your DSN etc. */);
// Your query.
$sql =
'SELECT * FROM posts WHERE ' .
'MATCH(theKey) AGAINST(? IN NATURAL LANGUAGE MODE) ' .
'AND uid = ? ORDER BY sgq_id LIMIT 5';
// Create prepared statement from query.
$statement = $pdo->prepare($sql);
// Bind the values and enforce data type.
$statement->bindValue(1, $key, PDO::PARAM_STR);
$statement->bindValue(2, $userid, PDO::PARAM_INT);
// Run query.
$statement->execute();
// Get query results.
$rows = $statement->fetchAll();
// Your magic ...

beginner php mysql : error trying to run a query

I'm trying to create a very simple web app that checks if an element is inside the database.
If the element is located at least one time in the DB, then echo "YES", otherwise if the element doesn't exist just echo "NO".
Here's my code :
$mysql = mysqli_connect(/* can't share anything here */) or die ("ERROR CONNECTING TO THE DB");
if(isset($_POST['submit'])) {
$theAddress = $_POST['url'];
$result = "SELECT * FROM data WHERE url = " . $theAddress;
$query = mysqli_query($mysql, $result);
if (!$query) {
printf("Error");
} else {
printf("NO ERROR");
}
The problem here is that PHP always echo "Error". Why?
In order to execute SQL queries successfully you need to put the string values inside quote.
So your query will be:
$result = "SELECT * FROM data WHERE url = '" . $theAddress . "'";
You need quotes around the value because it's a string.
$result = "SELECT * FROM data WHERE url = '" . $theAddress . "'";
But it would be better if you learned to use prepared queries with mysqli_stmt_bind_param(), then you don't have to worry about this.
Try with prepared statements like this:
$stmt = mysqli_stmt_init($mysql);
if (mysqli_stmt_prepare($stmt, 'SELECT * FROM data WHERE url = ?')) {
mysqli_stmt_bind_param($stmt, "s", $theAddress);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
Documentation:
http://us.php.net/manual/en/mysqli-stmt.prepare.php
http://us.php.net/manual/en/mysqli-stmt.get-result.php

PHP PDO MySQL count() prepared statement

I'm on a Web development course. Working with PHP PDO MySQL they teach us on a workshop to do this:
function countUsers($search) {
$and = '';
if ($search != '') {
$and = " AND user_name LIKE '%".$search."%'";
}
$total = $this->db->query("SELECT COUNT(id) as rows FROM users WHERE valid = 1" . $and)->fetch(PDO::FETCH_OBJ);
return $total->rows;
}
From my point of view this is totally wrong, the statement is not prepared and is passed directly from user input without any validation that can lead to SQL Injection, so I proposed this to the trainer (I know fetchColumn() would be more appropriate here but let's stick with this for the sake of the example):
function countUsers($search) {
$and = '';
$sqlSearch = "%$search%";
if ($search != '') {
$and = " AND user_name LIKE :username";
}
$sql = "SELECT COUNT(id) as rows FROM users WHERE valid = 1" . $and;
$sth = $this->db->prepare($sql);
if ($search != '') {
$sth->bindParam(':username', $sqlSearch, PDO::PARAM_STR);
}
$sth->execute();
$total = $sth->fetch(PDO::FETCH_OBJ);
return $total->rows;
}
Am I wrong? Are they wrong or we both wrong/right?
Yes you are right.
However, your code is not optimal. In fact, prepared statements are intended to make your code cleaner, not more bloated.
function countUsers($search) {
$sql = "SELECT COUNT(id) FROM users WHERE valid = 1 AND user_name LIKE ?";
$sth = $this->db->prepare($sql);
$sth->execute(["%$search%"]);
return $sth->fetchColumn();
}
Part of the cleanup I did is a mere trick - as you can always search for LIKE '%%' and match all rows (excluding ones where user_name is null though).
But the rest is just a proper use of PDO features:
you can always use positional placeholders
you can always avoid bindParam() call
you should use appropriate fetch mode

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."' ";

WHERE statement inside if condition in SQL

Can I do a WHERE clause inside an IF statement?
Like I want something like this:
$SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC");
$rows = mysql_fetch_array($SQL);
$email = $_SESSION['email_of_user'];
if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email)
Edit Server
<?php else : ?>
Add Server
<?php endif; ?>
Do I need (" where the WHERE statement is? Because I tried that and it didn't seem to work...
Or can I do it with an if condition inside of a where clause? Not sure of all these terms yet so correct me if I'm wrong...
You cannot mix up a query statement with PHP's statement. Instead write a query extracting desired results and check if there are any rows from that query.
I will show you an example:
$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query
$result = mysqli_query($query, $link); //Query the server
if(mysqli_num_rows($result)) { //Check if there are rows
$authenticated = true; //if there is, set a boolean variable to denote the authentication
}
//Then do what you want
if($authenticated) {
echo "Edit Server";
} else {
echo "Add Server";
}
Since Aaron has shown such a effort to encourage safe code in my example. Here is how you can do this securely. PDO Library provides options to bind params to the query statement in the safe way. So, here is how to do it.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection
//Create the Query Statemetn
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email');
//Binds Parameters in the safe way
$sth -> bindParam(':field', 1, PDO::PARAM_INT);
$sth -> bindParam(':email', $email, PDO::PARAM_STRING);
//Then Execute the statement
$sth->execute();
$result = $sth->fetchAll(); //This returns the result set as an associative array

Categories