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 . '%');
Related
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 6 years ago.
Improve this question
I have a query on my site and have recently been hacked because of it.
I have spent a good 2 hours looking how to convert this query so it is secure and have not got anywhere.
If anyone don't mind, could you please convert this one for me just so I can see what to do on the rest?
$camera_id = $_GET['camera_id'];
$cameras = mysqli_query($conn, "SELECT * FROM cameras WHERE id = $camera_id");
$camera = mysqli_fetch_array($cameras);
Try something like this.
$camera_id = $_GET['camera_id'];
$cameras = mysqli_prepare($conn, "SELECT * FROM cameras WHERE id = ?");
mysqli_stmt_bind_param($cameras, $camera_id);
$cameras->execute();
While you are making the switch, switch straight away to PDO. It's far better than mysqli
$db = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM cameras WHERE id = :camera_id");
$stmt->execute(array(":camera_id"=>$camera_id));
$result = $stmt->fetchAll();
or instead of fetchAll()
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'].' '.$row['field2']; //etc...
}
As you can see this is more readable. And if you later decide eto switch to postgresql the change is real easy.
This is using PDO and assumes that the camera id is a number (if it can contain non-numerical values swap the PARAM_INT for a PARAM_STR. The basic premise is that you separate the query from the variables and you bind the value of the desired item to a variable. Also note that you would need to alter the variables in the new PDO declaration to suit your own database. Note also that fetchAll() provides an associative array of the returned results - there are a number of other fetch() methods possible to give different outcomes - look for the official documentation.
$camera_id = $_GET['camera_id'];
$conn = new PDO('mysql:host=localhost;dbname=db', 'username', 'password');
$sql = "SELECT * from cameras where id = :cameraId";
$q = $conn->prepare($sql);
$q -> bindValue(":cameraId" , $camera_id, PDO::PARAM_INT);
$q->execute();
$cameraRows = $q->fetchAll();
foreach($cameraRows as $cameraRow){
$CID= $cameraRow["camera_id"];
//.... rest of the code
}
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
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
i got an db that i can add stuff in it with this sql statement using pdo type of connection .. :
$sql_createAD = "INSERT INTO `kijilikedb`.`advertise` (`AD_ID`, `AD_NAME`, `REF_STATE`, `REF_USER`, `REF_CAT`, `REF_SUB`, `REF_DESC`, `REG_DATE`, `EXP_DATE`, `AD_TYPE`, `AD_PRICE` , `IMAGE`) VALUES (NULL,'".$_POST['Title']."','".$_POST['state']."','',".$currentCAT.",'".$_POST['sub']."', ".$currentDescId.", '".$today."', '".$EXP."','".$_POST['type']."','".$_POST['Price']."','".mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']))."')";
$con->query($sql_createAD );
in big ..... im adding an article that contain information and everyting .... but when im adding the img to the database im using ".mysql_real_escape_string" that is a depreciated methode that i should use anymore ...... so now i want to replace it ... but i read there is no alternative for this in pfo ...... but im shure i can find an work around it ..... so plz help me finding it! :D
i find that maybe if im using an $con->prepare() for the insert and execute() for puting it in the db it could work ... but in doest for me ..... the error i get when i doing is :
SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters
look at the try i did :
$query = "INSERT INTO `kijilikedb`.`advertise` (`AD_ID`, `AD_NAME`, `REF_STATE`, `REF_USER`, `REF_CAT`, `REF_SUB`, `REF_DESC`, `REG_DATE`, `EXP_DATE`, `AD_TYPE`, `AD_PRICE` , `IMAGE`) VALUES (NULL,'".$_POST['Title']."','".$_POST['state']."','',".$currentCAT.",'".$_POST['sub']."', ".$currentDescId.", '".$today."', '".$EXP."','".$_POST['type']."','".$_POST['Price']."','".file_get_contents($_FILES['image']['tmp_name'])."')";
$preparedQuery = $con->prepare($query);
$preparedQuery->execute();
Here's how I would do it with a prepared statement with parameters:
$query = "INSERT INTO kijilikedb.advertise
SET AD_ID = :ad_id,
AD_NAME = :ad_name,
REF_STATE = :ref_state,
REF_USER = :ref_user,
REF_CAT = :ref_cat,
REF_SUB = :ref_sub,
REF_DESC = :ref_desc,
REG_DATE = :reg_date,
EXP_DATE = :exp_date,
AD_TYPE = :ad_type,
AD_PRICE = :ad_price,
IMAGE = :image";
This uses an alternative syntax for INSERT. It's a bit easier to read and easier to match up your column names with your query parameter placeholders. But this syntax doesn't support multi-row inserts.
Next, create an associative array with your values. The keys match the parameter placeholder names above (the leading colon character is not required).
When you use query parameters, you must not use any escape-string method (FWIW, PDO::quote() does escaping, but adds the quote marks as well).
$values = array(
'ad_id' => NULL,
'ad_name' => $_POST['Title'],
'ref_state' => $_POST['state'],
'ref_user' => '',
'ref_cat' => $currentCAT,
'ref_sub' => $_POST['sub'],
'ref_desc' => $currentDescId,
'reg_date' => $today,
'exp_date' => $EXP,
'ad_type' => $_POST['type'],
'ad_price' => $_POST['Price'],
'image' => file_get_contents($_FILES['image']['tmp_name'])
);
Then finally, the prepare/execute is a simple two lines of code:
$preparedQuery = $con->prepare($query);
$preparedQuery->execute($values);
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.'%'));
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?