LIKE query in PDO not working - php

PDO queries run fine, but when i try to use LIKE query it don't work and give error. i know i am doing something wrong, please if anyone can point out where i have gone wrong and how to run the the LIKE query properly.
<?php
/**
* Created by PhpStorm.
* User: HaiderHassan
* Date: 9/3/14
* Time: 9:52 PM
*/
header('Access-Control-Allow-Origin: *');
try {
$conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($_POST['searchFilter']){
$searchFilter = "%".$_POST['searchFilter']."%";
echo $searchFilter;
$stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
print_r(json_encode($results));
}
i have two columns in table(roomnames) roomID and roomName
i want to get the result of data which matches with the posted value.

You have multiple problems:
a) Vulnerable to SQL injection attacks
b) Lacking a space after LIKE, which means you're producing
... LIKE%foo%
c) Lack of quotes around your search parameter, so even if you did fix b), you'd still have a problem. it should be
... LIKE '$searchParameter'
^----------------^--- note the quotes

The statement should be prepared
if($_POST['searchFilter']){
$searchFilter = $_POST['searchFilter'];
echo $searchFilter;
try {
$conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT roomName FROM roomnames WHERE roomName LIKE ?");
$stmt->execute(array('%'.$searchFilter.'%'));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//print_r($results);
echo json_encode($result);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}

In this line:
$stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
There has to be a space behind the LIKE
You need to enclose the string between apostrophs to make it an actual SQL string
You should definitely use parametrized queries, because right now this is a gaping SQL injection hole (what if someone searches for ';delete from roomnames; select '?)

Related

Postgresql not binding in prepared statement for SELECT in PHP

<?php
try
{
global $db;
$user = 'postgres';
$password = '*****'; //For security
$db = new PDO('pgsql:host=localhost;dbname=dnd', $user, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $ex)
{
echo 'ERROR!!: ' . $ex->getMessage();
die();
}
$table = htmlspecialchars($_REQUEST['table']);
$idNum = htmlspecialchars($_REQUEST['id']);
try {
//$query = "SELECT * FROM $table WHERE id = $idNum"; This works
//$query = "SELECT * FROM $table WHERE id = :number"; This works
$query = "SELECT * FROM :tableName WHERE id = :number";
$statement = $db->prepare($query);
$statement->bindValue(":tableName", $table, PDO::PARAM_STR);
$statement->bindValue(":number", $idNum, PDO::PARAM_INT);
$statement->execute();
$info = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $excep) {
echo "Opps: " . $excep->getMessage();
die();
}
Okay I'm going crazy here trying to get this to work.
I have a database set up that I need to query from. I receive the query from an AJAX request with the name of the table I want and the id for the item. When I try to query with both variables, the binding does not occur in the prepared statement and instead I get this error code
Opps: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "$1" LINE 1: SELECT * FROM $1 WHERE id = 1 ^
When I have just the straight PHP variables it works fine so I know it can work, but when I want to bind multiple it seems to fail and give a variable number as above.
I can also get it to work if I simply have one of the variables bound, such as the second commented out query in the code - this only works tho if I have the variable I want at the end and not if I wanted to lookup the table spot. (I.E.
$query = "SELECT * FROM :tableName WHERE id = $idNum"; does not work)
I need to cleanse the variables to prevent SQL injection, but I can't do that without binding the variables in a prepared statement. Any help would be appreciated!
According to the PHP manual you can't bind a tablename. As you mentioned it, you can replace it by a variable, but you can't replace it with a placeholder.
So the only solution that will work for you is the query you have above:
$query = "SELECT * FROM $table WHERE id = :number"
This will be what you're looking for. If you want to make it safe for injection, you have to find another way. (Regex for example).
Ref: http://us3.php.net/manual/en/book.pdo.php#69304

need to SELECT and show all entries written by specific user and count it

I need to SELECT and show all entries written by specific user and number of his/her total entries
<?php include 'helperl.php'; include 'dbconn.php';
$name=$_GET['id'];
$sql="SELECT * FROM entries WHERE writer_user LIKE '%$name%'";
$result=$conn->query($sql);
$num_entry= count($result);
echo "$num_entry";
?>
First the LIKE option that you did will get you all the name that contain $user
Your query should be like
SELECT nb
FROM (SELECT writer_user,count(*) as nb
FROM entries
WHERE writer_user=you_var
Group BY writer_user)
For getting all the entries of specific user
SELECT *
FROM entries
WHERE writer_user=you_var
u can do a join in one query to get the information you wanted but there will be a duplication in the count attribut.
exemple :
entrie count
entrie1 4
entrie2 4
entrie3 4
entrie4 4
hope i helped you.
you should use SQL COUNT function to do this (SQL COUNT function
)
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Your code can look like this
<?php
try {
$name = htmlentities(strip_tags($_GET['id']));
$sql = "SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%$name%'";
// create pdf instance
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%name%'");
$stmt->bindParam('name', $name);
$stmt->execute();
$result = $conn->query($stmt)->fetchAll();
var_dump($result);
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$conn = null;
?>

PHP - Count SQL Results Per Day

So I have a table called Userswhich contains a table structure like this:
Lets say I have a mysql table called 'signups' with the following values:
UID|Name|Regdate
1|Admin|2014-03-04 10:51:01
2|Demo|2014-05-04 09:51:05
I want to create a graph showing how many people signed up in one day. I used this SQL Query:
SELECT DATE(regdate) AS `Date` , COUNT(*) AS Signups FROM `users` GROUP BY DATE(regdate)
It gave me an output of:
Date|Signups
2014-03-04|1
2014-05-04|1
I wanted the output in a PHP File so I made this
<?php include_once("inc/db.php"); ?>
<?php
$query ="
SELECT DATE(regdate) AS `Date`
, COUNT(*) AS Signups
FROM `users`
GROUP BY
DATE(regdate)
";
$query_params = array(
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
echo $result;
?>
When I try to access the page, the result I get should be same thing I got from the SQL Query. However the result I get is 1. As you can see, I am using PDO. I am a beginner please help me please. :)
Do you use mysqli or PDO? Anyway execute does not do the job of returning the eventual result, assuming you use PDO, you have to:
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
foreach($stmt->fetchAll() as $fetch)
{
// do something
}
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
echo $result;

PHP PDO, connection works buy query not executing

i am new to PDO.
Here is what i have done so far,
Created file "pdotest.php"
Code Inside that file
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$stmt = $conn->query("SELECT roomName FROM roomName.roomnames");
$results = $stmt->fetchAll();
$stmt->closeCursor();
print_r($results);
var_dump($results);
it should display some results from database but instead it says 500 internal server error in firebug, but no error on screen, its a white blank screen.
$stmt = $conn->query("SELECT roomName FROM roomName.roomnames");
try this instead:
$stmt = $conn->query("SELECT roomName FROM roomnames");
The select syntax is (basically):
SELECT column[, another_column, ...] FROM tablename[WHERE condition][ORDER BY some_column ASC/DESC];`
As you are setting the error mode to PDO::ERRMODE_EXCEPTION, you'll need to use try/catch to see any errors. This brings the burden of wrapping try/catch statements around your db queries.
Check your php log file for the exact php error - a white screen is shown as php is probably set up not to display errors on screen.
I'd check this part:
SELECT roomName FROM roomName.roomnames
Are you really trying to select roomName column from a table named roomName.roomnames? Should it not be the other way around like
SELECT roomnames FROM roomName
?

PDO prepared statements in functions [duplicate]

This question already has answers here:
How do I loop through a MySQL query via PDO in PHP?
(3 answers)
Closed 9 years ago.
I am currently using MySQL with PHP but am looking to start MySQLi or PDO
I have while loops like:
$sql="select from ... ";
$rs=mysql_query($sql);
while($result=mysql_fetch_array($rs))
{
$sql2="select from table2 where id = $result["tbl1_id"] ";
}
If I put my MySQLi or PDO queries into a function how can I run things like the above? Doing while loops with queries inside the while loops?
Or is if easier to not do the functions at all and just run the prepared statements as normal?
You wouldn't. And to be honest.. Even in the old days you would not do it this way, but like this:
$sql="select from ... ";
$rs=mysql_query($sql);
$ids = array()
while($result=mysql_fetch_array($rs))
{
$ids[] = $result["tbl1_id"];
}
$sql2="select from table2 where id in ".implode(',', $ids) .";
Or even better, you use a join to run the query just once, on all the tables that need to provide info.
In PDO you can do the same thing. Get all the ID's and the execute a query
I usually take the approach of preparing the query and not using a function. Also I am not clear as to what exactly it is that you want. You want to make your queries as quick and efficient as possible so you should not look to run a while look within another while loop.
This is how my PDO queries usually look
My connection:
$host = "localhost";
$db_name = "assignment";
$username = "root";
$password = "";
try {
$connection = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
MY query:
$query = "SELECT * FROM Table";
$stmt = $connection->prepare( $query );
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
}
It's a duplication question like oGeez say, you have to learn how to code PDO in PHP and other before asking question,
this is the answer:
$dbh = new PDO("mysql:host=" . HOST . ";dbname=" . BASE, USER, PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = 'SELECT * FROM table';
$stmt = $dbh->query($query);
$items = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($items as $item {
print_r($item);
}
the main reason to put it in a function would be if you use the query in multiple files. i have a web app with many queries and i like to keep them in a separate file so that they're easier to track down if i need to make changes. the main thing is that you 1) have to pass your database as a parameter and 2) return the results
function pdoquery($db, $parameter){
$query = "SELECT * FROM table WHERE column=?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $parameter, PDO::PARAM_STR); //or PARAM_INT
if (!$stmt->execute()) {
echo "Could not get results: (" . $stmt->errorCode . ") " . $stmt->errorInfo;
exit;
}
else
$result = $stmt->fetch();
$db = null;
return $result;
}
but as others have mentioned, if its only used once, there's no need for a function, and looping through the results is best done outside of the function as well. however, it is possible to do it inside the function if you want to.

Categories