Wordpress prepared LIKE query [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to use a prepared LIKE query within Wordpress, but it doesn't seem to be working. I've followed the codex for the syntax.
public function userByJobId($id){
global $wpdb;
$result = $wpdb->get_row($wpdb->prepare( "SELECT * FROM use_users WHERE use_job_id LIKE = d%;", '%' . $wpdb->esc_like((int)$id)) . '%');
if(!empty($result)){
return $result;
}
return false;
}
Calling the method like so:
$userid = 1
$user = new Users();
$user_id = $user->userByJobId($userid);
Cant see where the issue lies..

A few points have been made already:
Syntax for prepare() is the same as that for sprintf; a decimal placeholder is %d, not d%
The LIKE keyword shouldn't be followed by an equals, just the expression to test against
A few other things:
You concatenate the LIKE % wildcard after the closing parenthesis for prepare(), where it should be concatenated before
get_row() will return an object by default, not just the ID, which is a property of the object returned
public function userByJobId($id){
global $wpdb;
$result = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}users WHERE {$wpdb->prefix}job_id LIKE %d;",
'%' . $wpdb->esc_like((int)$id) . '%'
)
);
if($result){
return $result->ID;
}
return false;
}

The wordpress class reference tells me that:
Possible format values: %s as string; %d as integer (whole number);
and %f as float.
When you want to prepare a query with a like comparison you should double escape percentages.
So change
$result = $wpdb->get_row($wpdb->prepare( "SELECT * FROM use_users WHERE use_job_id LIKE = d%;", '%' . $wpdb->esc_like((int)$id)) . '%');
To
$result = $wpdb->get_row($wpdb->prepare( "SELECT * FROM use_users WHERE use_job_id LIKE %%%d%%;",(int)$id));
You also don't have to escape values (the prepare method does that for you).
Warning: Non tested code

Related

Use WHERE IN with PDO PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to build a shopping cart using PHP, I get a list of IDs from the products added to the basket, I then want to query my database with these IDS using a WHERE IN SQL statement to get the details of the items added to the basket.
At the moment my query just comes back with false.
if(isset($_SESSION["cart"])) {
foreach ($_SESSION["cart"] as $id => $value) {
$ids .= $id . ',';
$count += $value['quantity'];
}
$query = $database->find_item_db($ids);
EDIT I have now changed my function to use the PDO syntax.
function find_item_db($product_code) {
$query = substr($product_code, 0,-1);
$product_codes = explode(",", $query);
$product_code_new = "(".implode("', '", $product_codes).")";
//we need to get product name and price from database.
$sql = "SELECT * FROM `Sweets` WHERE `Sweet_ID` IN :id";
$statement = $this->connection->prepare($sql);
$statement->bindParam(':id', $product_code_new);
$statement->execute();
return $done = $statement->fetchAll();
}
However this is still returning nothing, I get this error in my logs.
/var/www/html/sweetshop/partials/categories-nav.php(32): Database_Functions->find_item_db('1,10,6,23,')\n#2 /var/www/html/sweetshop/category.php(17): include('/var/www/html/s...')\n#3 {main}\n thrown in /var/www/html/sweetshop/classes/class-database-functions.php on line 139, referer: http://localhost/sweetshop/category.php?type=Chocolate
I know my connection works fine as all my other queries work perfectly.
1. Incorrect syntax
If $ids is something like:
$ids = "1,2,3,4,5";
Then the query is:
SELECT * FROM `Sweets` WHERE `Sweet_ID` IN (1,2,3,4,5)
Which is incorrect because each value needs to be wrapped in single quotes:
function find_item_db($product_code){
$query = substr($product_code, 0,-1);
//Wrap each product id
$product_codes = explode("," $product_code);
$product_codes = "'".implode("', '", $product_codes)."'";
//.......
}
That way the query will read:
SELECT * FROM `Sweets` WHERE `Sweet_ID` IN ('1', '2', '3', '4', '5')`
2. Mixing SQL APIs
mysqli_* syntax and PDO syntax are not interchangeable. bind_param() is for PDO, however your query is using mysqli.
When you are using $statement->bind_param(':id', $new);, what are you binding? There is no :id value in the query, and therefore the line is unnecessary as well as incorrect SQL query format!

how to treat special characters as regular characters pdo [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Im a having a problem with this piece of code, im using a form to pass a value to a search engine, what I want to do is to read special character as regular character, becuase if i type %sam% it reads this as part of the 'query', not like a regular string(normal character)
it is possible to
$search = $_GET['query'];
$query = "SELECT * FROM mobiles WHERE (`name` LIKE :search) or (`type` LIKE :search)";
$query_params = array(':search' => mysql_real_escape_string( $search ));
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
use quote from your pdo Connection Object
$db->quote($search ); //Assuming your connection is $db
Though % is special in that, it is legal in a string, so you would probably have to escape it manually.
$search = str_replace("%", "\%", $search),
Some points:
mysql_real_escape_string has no use whatsoever here. named parameters relieves you from thinking about that
with mysql you can't use the same named placeholder :search, either you make two of em (:search1,:search2) either you set ATTRIBUTE_EMULATE_PREPARES=>TRUE when building PDO
When working with LIKE in PDO you must be sure to pass % around the string you submit to the placeholder: array(':search' => '%' . $search . '%');

Calling PDO inside a Function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am following a project for creating spell checker. However, rather than using regular mysql, i decided to go with PDO. So i converted code to PDO. I am stuck at one point and not sure why i can't call PDO inside any function even after declaring global variable. What i am doing wrong?
Purpose: I have loaded 100k+ words in a table and want to find similar words by searching one word.
<?php
include "db.inc.php";
function spellcheck($word){
global $db;
$output = array();
$word = $db->quote($word);
$words = $db->prepare("SELECT words FROM english WHERE SUBSTRING(word, 0, 1) = '.substr ($word, 1, 2)'");
$words->execute();
while (($words_row = $words->fetch(PDO::FETCH_ASSOC)) !== false){
echo $words_row['word'];
}
}
if (isset($_GET["word"]) && trim($_GET["word"]) !== null){
$word = $_GET["word"];
$spellcheck = spellcheck($word);
}
?>
<form action="" method="GET">
Please type word to check: <input type="text" name="word">
<input type="submit" value="Check">
</form>
Try the following:
function spellcheck($word){
$db = new PDO ("mysql:host=localhost;dbname=splcheck", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = "SELECT words FROM english WHERE SUBSTRING(word, 0, 1) = :word";
$stmt = $db->prepare($query);
$stmt->execute(array(':word'=> substr ($word, 1, 2)));
$output = array();
while ($words_row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $words_row['words'];
}
return $output;
}
Don't use global, pass the connection as argument instead
Make sure you prepare your query properly
Your function was not returning the output
Remove !== false from the while loop its redudant
Avoid typos you forgot s on $words_row['words'];
Using like statement:
$query = "SELECT `words` FROM english WHERE `word` = LIKE :word";
$stmt = $db->prepare($query);
$stmt->execute(array(':word'=>'%'.$word.'%'));

how to use php variables make query for sqlite3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
<?php
/**
* Simple example of extending the SQLite3 class and changing the __construct
* parameters, then using the open method to initialize the DB.
*/
class MyDB extends SQLite3
{
function __construct()
{
$this->open('wifin.db');
}
}
$db = new MyDB();
$mac = 'test';
$ssid = $_POST['ssid'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$db->exec("INSERT INTO wifinTb (mac,ssid,lat,lon) VALUES ($mac,$ssid,$lat,$lon)");
$result = $db->query('SELECT * FROM wifinTb WHERE mac=$mac');
var_dump($result->fetchArray());
?>
i'm not sure how to use variables in php5, $mac should be a string, when i directly use mac=$mac, it return me bool(false), which means can't find, but when i use mac='test', it gives me result.
Never ever use string concatenation or replacement to put values into SQL statements; this will give you formatting problems (as you've seen) and allow SQL injection attacks.
Instead, use parameters:
$stmt = $db->prepare('INSERT INTO wifinTb(mac,ssid,lat,lon) VALUES (?,?,?,?)');
$stmt->bindValue(1, 'test');
$stmt->bindValue(2, $_POST['ssid']);
$stmt->bindValue(3, $_POST['lat']);
$stmt->bindValue(4, $_POST['lon']);
$stmt->execute();
$stmt = $db->prepare('SELECT * FROM wifinTb WHERE mac = :mac');
$stmt->bindValue(':mac', $mac);
$result = $stmt->execute();
What you initialize $mac with 'test', is what you are doing is assigning a string (PHP recognizes anything inside '' or "" as a string) to $mac. The value of this string is test. So you still need to surround the value in the query with '':
$db->exec("INSERT INTO wifinTb (mac,ssid,lat,lon) VALUES ('$mac','$ssid','$lat','$lon')");
$result = $db->query('SELECT * FROM wifinTb WHERE mac=$mac');
Is currently being seen as one long string. You could get around this quickly by changing it to:
$result = $db->query("SELECT * FROM wifinTb WHERE mac='" . $mac . "'");
However, you'd be better reading up on PDO or mysqli bind functions rather than injecting like that.
Hope that helps?

query function breaks mysteriously [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a Database class which has multiple functions to execute queries. One of them is the simplest of them all:
public function query($query) {
return $this->_link->query($query);
}
$this->_link->query works in other cases, so it should work here. From a file that has an instance of a class, I do this:
function createLineChart() {
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
createLineChart();
but it breaks on the $result line. The query is also valid, I've testid it. Am I missing something?
Your problem is $db is out of scope of the createLineChart() function. You can either use the global method:
function createLineChart() {
global $db; // <-- make the db var become available
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
Or pass the $db object to the function as an argument:
function createLineChart($db) {
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
createLineChart($db);
More info about Variable Scope on the Manual.
function createLineChart() {
var_dump($db);
// this should probably return 'undefined'
global $db;
// so globalize it!
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
If $db is a class variable, then you need to refer it as:
$result = $this->db->query($query);

Categories