PDO with multiple LIKE on single column - php

I have not been able to find a suitable answer for why my PDO query isnt working with multiple "like" statements on the same column. When using a Joomla framework i can execute the query successfully .. i created output to show the query here:
Joomla core query function Output
SearchValue: Array (
[0] => Test
[1] => Name
)
Query output from joomla "$query->__toString()" command:
SELECT id,name
FROM portal_users
WHERE name LIKE '%Test%' AND name LIKE '%Name%'
**data Set**
id name
1 Test Name
2 Other name
3 Test Example
**Query Results**
Test Name
But when I create the same query using PDO it does not filter by both parameters and returns no results instead.
PDO submission and Output
SearchValue: Array (
[0] => Test
[1] => Name
)
Query submitted to PDO:
SELECT id, name
FROM portal_users
WHERE name LIKE :var1 AND name LIKE :var2
PDO Data: Array (
[:var1] => %Test%
[:var2] => %Name%
)
**data Set**
id name
1 Test Name
2 Other name
3 Test Example
**Query Results**
No results
I am at a loss to explain the cause of identical queries not working unless the PDO values are treated differently. Any input would be appreciated.
--UPDATE--
I have followed the example and request of user yourcommonsense and created the following code to validate my concern:
// first let's create a table
// note that table is temporary so it won't pollute your database
$createQuery = "CREATE temporary TABLE test_users (id int auto_increment primary key, name varchar(255))";
$db->query($createQuery);
// then fill it with sample data
$insertQuery = "INSERT INTO test_users (name) VALUES ('Test Name'),('Another Name'),('Test Example')";
$db->query($insertQuery);
// now let's see if we have our data back all right
$dataCheck = "SELECT name FROM test_users";
echo "Test Query on temp table:\n$dataCheck\n";
$data = $db->query($dataCheck)->fetchAll(PDO::FETCH_ASSOC);
echo print_r($data,true);
// now let's test with a hardcoded value
$hardCodedQuery = "
SELECT id, name
FROM `test_users`
WHERE name LIKE '%test%' AND name LIKE '%name%'
";
echo "Harcoded Query on temp table:\n$hardCodedQuery\n";
$data = $db->query($hardCodedQuery)->fetchAll(PDO::FETCH_ASSOC);
echo print_r($data,true);
// and finally, with a prepared statement
$preparedQuery = "
SELECT id, name
FROM test_users
WHERE name LIKE :var1 AND name LIKE :var2
";
echo "Prepared Query on temp table:\n$preparedQuery\n";
$stmt = $db->prepare($preparedQuery);
$vars = array(":var1" => '%Test%', ":var2" => '%Name%');
$stmt->execute($vars);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo print_r($data,true);
I see that he is correct about my understanding as both the hardcoded statement, and the prepared statement in this code snippet do indeed result in the same results i was hoping to get from my original post above. I am still at a loss to explain why the original posted queries are not working in the same way. As stated earlier, the Joomla query and the PDO query I am running have the same structure, but the PDO above returns a successful query of 0 results. I may need to compare table structure? I will keep researching, but any other thoughts would be appreciated.
Oddly enough, the MCVE code running on my actual database works as it should, so i have to see what's different on my actual page vs. the MCVE.
Test Query on production table:
SELECT id, name FROM portal_users LIMIT 3
Array (
[0] => Array ( [id] => 244 [name] => User One )
[1] => Array ( [id] => 261 [name] => User Two )
[2] => Array ( [id] => 262 [name] => User Three )
)
Harcoded Query on temp table:
SELECT `users`.`id`,`users`.`name`
FROM `portal_users` AS `users`
WHERE `users`.`name` LIKE '%silver%' AND `users`.`name` LIKE '%tiger%'
Array (
[0] => Array ( [id] => 7101 [name] => Silver Tiger )
)
Prepared Query on temp table:
SELECT `users`.`id`, `users`.`name`
FROM portal_users AS `users`
WHERE `users`.`name` LIKE :var1 AND `users`.`name` LIKE :var2
Supplied variables for prepared statement:
Array ( [:var1] => %silver% [:var2] => %tiger% )
Array (
[0] => Array ( [id] => 7101 [name] => Silver Tiger )
)
Even when I copy and paste the query my PHP creates it will execute in a SQL query window through Navicat and return results...
SELECT id, name
FROM portal_users
WHERE name LIKE CONCAT('%','sil','%') AND name LIKE CONCAT('%','tig','%')
but when submitted via PHP PDO with the ? and array of variables, it has no results. still researching.

Related

SQL result array, from PDO query, has duplicated values [duplicate]

This question already has answers here:
sql PDO fetchall duplicate object keys?
(2 answers)
Closed 2 years ago.
I have a mysql table that has the following fields
STUDENTID | FIRSTNAME | SURNAME | DOB | SCHOOLID
A form is used for a user to search for a student and output all those with matching first and surnames
The following SQL statement returns the PDO fine
$sqlstmnt2 = 'SELECT * FROM students WHERE firstName = :fname AND surname = :sname AND schoolID = :schoolID';
// prepare PDOstatement as $query ...
// ...
$query->execute();
$_SESSION['foundPupils'] = $query->fetchAll();
However, when I pass this through to another PHP page in a session variable, I'm confused as to how to access each field individually. I have the following code
foreach($_SESSION['foundPupils'][0] as $found){
echo($found);
}
This outputs the found data but the issue is that it outputs it twice, and it's just a long string of data which can't be formatted nicely. My questions are:
Why does each result output twice?
How do I access the individual fields within this array (kind of like foundPupils[0]['firstName'] for example?
According to the documentation, both the method PDOStatement::fetch and PDOStatement::fetchAll accepts a $fetch_style parameter. If not set, the default value is PDO::FETCH_BOTH. That means the fetched array will both reference the fields by position (e.g. 0, 1, 2) and by column name (e.g. "firstName", "surname").
So by default, your fetched results would be something like this:
Array
(
[0] => Array
(
[name] => apple
[0] => apple
[colour] => red
[1] => red
)
[1] => Array
(
[name] => pear
[0] => pear
[colour] => green
[1] => green
)
[2] => Array
(
[name] => watermelon
[0] => watermelon
[colour] => pink
[1] => pink
)
)
To fix this, you need to call your fetch function (I suppose it is PDOStatement::fetchAll) with PDO::FETCH_COLUMN as the fetch style:
$query->execute();
$_SESSION['foundPupils'] = $query->fetchAll(PDO::FETCH_COLUMN);
Query results are returned and stored in a result object. Therefore, you have to iterate through the result either using xxxx_fetch_array or xxxx_fetch_row. for example
$sql='SELECT * FROM table_name';
$result = mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
echo $row['COLUMN_NAME'].'<br />';
}

Fetch column name from SQL QUERY STRING in PHP

I want to fetch the alias column names from a query. Here I have not executed the query yet. The query is just in string format.
$query= "select id as id,name as 'Full_Name',caddress as 'Company_Address',paddress as 'Permenant_Address' from users"
From above query I want results like: id, Full_Name, Company_Address, Permenant_Address
I have tried to make it using explode function but it gives quite different results as I expect.
print_r(explode('as',$str));
O/P: Array ( [0] => select id [1] => id,name [2] => 'Full_Name',caddress [3] => 'Company_Address',paddress [4] => 'Permenant_Address' from users )
How to achieve the exact output I wanted?

Showing related items from database

I'm trying to fetch a value from my first sql query "Engine.type" and put this in a variable so I can use in another query. However instead of echoing the rows of similar engine type its echoing the whole table. Anyone know the problem?
Here is the first query:
$stmt = $pdo->prepare("SELECT
Owner.id,
Engine.type,
Engine.top_speed,
Engine.acceleration,
Car.number_plate,
Car.image,
Car.colour,
Car.price
FROM
Car
INNER JOIN
Model ON Car.model_id = Model.id
INNER JOIN Engine ON
Car.engine_id = Engine.id
INNER JOIN Owner ON
Car.Owner_id= Owner.id
WHERE
Model.id = :id");
$stmt->bindValue(':id',$carId);
$stmt->execute();
$car=$stmt->fetchALL();
Here is where I want the value you to go:
$simlar = $car['type'];
$stmt1 = $pdo->prepare('SELECT * FROM Car INNER JOIN Engine ON Car.engine_id
= Engine.id WHERE Engine.type LIKE :enginetype LIMIT 3'); //search for car
with simlar engine type
$stmt1->bindValue(':enginetype','%'.$simlar.'%');
$stmt1->execute();
$simlaritem=$stmt1->fetchALL();
You are calling fetchAll() on your results for the first query, and storing it in $car. This means that $car is an array of arrays containing the results.
Are you looping through $car? My guess, from the code you've posted, is that if you did a var_dump($car), you would see that actually have to have $simlar = $car[0]['type'];. Otherwise, $simlar would have a blank value (since there is no $car['type']), and thus your second query is just searching for WHERE Engine.type LIKE '%%'.
See the examples in the PHP documentation for PDO's fetchAll() for more details.
For clarity, I believe you are expecting $car to return something like this:
Array
(
[id] => 1
[0] => 1
[type] => SUV
[1] => SUV
...
)
But in reality, $car actually looks like:
Array
(
[0] => Array
(
[id] => 1
[0] => 1
[type] => SUV
[1] => SUV
...
)
)

PHP - SQLite unexpected return array results

First time playing with SQLite, I've created a database and table and set the column id as the primary key unique.
I've inserted some data into the table and can see the data when I do :
SELECT * FROM members;
However when I run the following query I'm not getting the results I expected.
$result = $db->query("SELECT * FROM members WHERE plan = 'User' AND id = '$users_id'");
echo "<pre>";
print_r($result->fetchArray());
echo "</pre>";
I get:
Array
(
[0] => 124578986532-784512986452
[id] => 124578986532-784512986452
[1] => User
[plan] => User
[2] => 54890
[phone] => 54890
[3] => 698-78450
[staffID] => 698-78450
[4] => WestWing
[location] => WestWing
[5] => 1
[active] => 1
)
Which is the correct result, but why do I get duplicates for each returned entry ?
ie: Why [0] & [id], [1] & [plan] ??
As each users ID is unique searching for it will only ever return one result set, how do I use the results as variables I can use elsewhere within the page ?
eg: $id = $result['id'] ?
Thanks
fetcharray contains numerical array and associative array, so your result should be
For Named index array
$result = $db->query("SELECT * FROM members WHERE plan = 'User' AND id = '$users_id'");
echo "<pre>";
print_r($result->fetchArray(PDO::FETCH_ASSOC));
echo "</pre>";
Here the Crossponding Data
$result->fetchArray(PDO::FETCH_BOTH) -The rows are arrays with both numeric and named indexes
$result->fetchArray(PDO::FETCH_ASSOC) -The rows are arrays with named indexes.
$result->fetchArray(PDO::FETCH_NUM) - The rows are arrays with numeric indexes.

PHP PDO execute() returning duplicate results

For this code:
$title = '0';
$subTitle = '1';
$tableName = 'someString';
$stmt = $dbh->prepare("SELECT `".$title."`, `".$subTitle."` FROM `".$tableName."_data` WHERE `id` = :key");
$stmt->bindValue(':key', '127');
$stmt->execute();
$result = $stmt->fetchAll();
print_r($result);
I get $result as this:
Array
(
[0] => Array
(
[0] => 91651
[1] => 91651 - DESCRIPTION
[2] => 91651 - DESCRIPTION
)
)
When the expected result should be this:
Array
(
[0] => Array
(
[0] => 91651
[1] => 91651 - DESCRIPTION
)
)
When I run the same query in mySQL, it returns the expected result. When it is executed via PHP PDO, it adds a duplicate.
Thanks!
Use fetchAll(PDO::FETCH_ASSOC) instead of fetchAll().
Solved by checking with someone better at databases than myself...
I foolishly named the columns as integer values.
So, what appeared as "duplicate values" was just the fact that the column number and the column name were the same!
In conclusion, I am bad at database structure.
Try to check the fetch_style and fetch_argument and set it to a value you need.
see sample #3:
http://www.php.net/manual/en/pdostatement.fetchall.php
sometimes dep. on your php version/pdo version there is a bug when using bindvalue.
try to avoid that and use sample #3 instead.
You could change to using fetch() instead of fetchAll(), that will return one row. But I'd just ensure in the database that id is unique.

Categories