Fetch column name from SQL QUERY STRING in PHP - 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?

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 />';
}

PDO with multiple LIKE on single column

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.

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.

Joining more than two mysql tables then manipulating rows into grouped multidimensional arrays

I'm trying to join multiple myqsl tables and then process resulting arrays using PHP but I'm having problems manipulating my data to get the groupings I'd like.
table.users
+--------------- uidname
table.profile_values
+----------------------- fiduidcategory_value
table.profile_fields
+--------------------- fid category_title
Here is my sql query:
SELECT users.name, profile_fields.category_title, profile_values.category_value FROM profile_values
INNER JOIN profile_fields
ON profile_values.fid=profile_fields.fid
INNER JOIN users
ON users.uid=profile_values.uid
ORDER BY users.name ASC
Using I while loop over fetch_array(), as expected, I get an array for each row number which looks something like:
Array (
[0] => Array (
[name] => Bob
[category_title] => Occupation
[category_value] => IT
)
[1] => Array (
[name] => Bob
[category_title] => Previous Experience
[category_value] => Very little.
)
...
)
The output I'm actually looking to generate is:
Array(
[name] => array(
[category_title 1] => value 1
[category_title 2] => value 2
...
)
....
)
I've spent the vast part of a day looking at various examples and haven't been able to find one that helps me understand the best place to interject and group my data. I've seen examples using GROUP_CONCAT, which is similar to what I want, but I'd like to keep my data in arrays if possible.
Should I be using a nested foreach loops after I have my rows assigned to arrays, using a GROUP BY in my sql statement, or a combination of both?
Use php to create the array you want then. Maybe something like:
$result = mysql_query($sql) or die(mysql_error());
$newArray = array();
while($row = mysql_fetch_assoc($result)){
$newArray[$row['name']][$row['category_title']][] = $row['category_value'];
}

Categories