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

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

Related

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.

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.

Results from mySQL using php show twice

I am connecting to my SQL server getting information from it using the following code:
if ($_POST['searchdb']) {
$searchi="".$_POST['search'];
$query = "SELECT * FROM consume WHERE type LIKE '%{$searchi}%' OR description LIKE '%{$searchi}%'";
if($result= mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
print_r($row);
}
}
}
I have each value stored only once in my database but I get the following output:
Array
(
[0] => RF Connector
[Type] => RF Connector
[1] => Male N Type Angle Cable Mtg.
[Description] => Male N Type Angle Cable Mtg.
[2] => Carousel
[Location] => Carousel
[3] => 2
[Drawer] => 2
[4] => Test
[Supplier] => Test
[5] => 12345678
[Order Code] => 12345678
[6] => 1
[id] => 1
)
Why does the data seem to appear twice? Or is this normal?
This is normal behaviour, see here http://php.net/manual/en/mysqli-result.fetch-array.php
If you want numeric indices use this
mysqli_fetch_array($result,MYSQLI_NUM);
and for associative indices use this
mysqli_fetch_array($result,MYSQLI_ASSOC);
If you don't pass any parameter you will get an array containing both.
Because you're using mysqli_fetch_array which puts two copies of the data into the result, once using the column number (starting from the left most column, numbered as 0) and once using the column's name.
You might find using mysqli_fetch_assoc instead of mysqli_fetch_array to be more useful, you get one copy of the data and you get useful column names.
this is because you used while mysqli_fetch_array($result)
^^^^^
it will give you both object and associative
use while mysqli_fetch_assoc($result)
you will get associative values
Yes, it is normal when using mysqli_fetch_array
Replace it with mysqli_fetch_assoc and you will get associative array which contains data only once or use mysqli_fetch_row to get enumerated array which also contains data only once.
source:
http://php.net/manual/en/function.mysql-fetch-assoc.php
http://php.net/manual/en/function.mysql-fetch-row.php

inserting to database in one shot an array mysql

hello all i am having a variable $document_ids=1,2,4,5,8,99,102 and i need to insert each of them individually to my database table like
$shaeredata=mysqli_query
($conn,"insert into docs (dcid,pid) values
('$dcid','$pid'),('$dcid2','$pid'),('$dcid3','$pid'),('$dcid4','$pid')");
//dcid is each id from the variable $document_ids=1,1022,4,5,8,99,102
//$dcid=1,dcid2=1022,$dcid3=4 ...... pid is same for all
the problem is that how do i put the values to database as i dont what document_id is going to be there it can be any seperated by coma.
$document_id=Array
(
[0] => 1
[1] => 4
[2] => 5
[3] => 999
[4] => 6
[5] => 7
[6] => 8
) // i have converted it to an array all of these are $dcid $pid=23 for all
I assume you really mean that $documement_ids isarray(1,2,4,5,8,99,102). If it's a string, you can useexplode` to split it into an array.
You can create an array of all the value pairs, and then use implode to connect them with commas.
$values = implode(',', array_map(function($dcid) use ($pid) {
return "('$dcid', '$pid')";
}, $document_ids);
$sql = "INSERT INTO docs (dcid, pid) VALUES $values";
mysqli_query($conn, $sql);

PHP Array insert into MySQL table as individual rows

I am trying to insert multiple rows in a MySQL table from PHP arrays. I managed with with help of other members to get set of values in a pair of brackets but when i try to insert this i get "Error: Column count doesn't match value count at row 1" I donot know where am i going wrong. my codes are as below: (The number of values i get vary according to user input)
$docno1=array();
$serialno = array();
$acc_name = array();
$debit = array();
$credit = array();
for ($i=1;$i<=$rowcount;$i++)
{
//echo 'Accountname'.$i.' :'.($_GET['accname'.$i]).'<br>';
$docno1 [] = ($_GET['docno']);
array_unshift($docno1,"");
unset($docno1[0]);
$serialno [] = $i;
array_unshift($serialno,"");
unset($serialno[0]);
$acc_name[] = ($_GET['accname'.$i]);
array_unshift($acc_name,"");
unset($acc_name[0]);
$debit[] = ($_GET['DrAmount'.$i]);
array_unshift($debit,"");
unset($debit[0]);
$credit[] = ($_GET['CrAmount'.$i]);
array_unshift($credit,"");
unset($credit[0]);
}
$sum_dr = array_sum ($debit);
$sum_cr = array_sum ($credit);
echo ' values of $multi<br>';
$multi = array(
($docno1),
($serialno), //Array for a row of fields
($acc_name),
($debit),
($credit),
($docno1)
);
print_r($multi);
$new = array();
foreach($multi as $key=>$value) {
$new[] = "'".implode("','", $value)."'";
}
echo '<br>Values of $new <br>';
print_r($new);
$query = "(".implode("), (",$new).")";
echo $query.'<br>';
mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());
echo "Inserted successfully";
die;
The results i get are :
values of $multi
Array
(
[0] => Array
(
[1] => 3434
[2] => 3434
)
[1] => Array
(
[1] => 1
[2] => 2
)
[2] => Array
(
[1] => Lemon
[2] => Kidney Beans
)
[3] => Array
(
[1] => 20
[2] => 10
)
[4] => Array
(
[1] => 0
[2] => 0
)
[5] => Array
(
[1] => 3434
[2] => 3434
)
)
Values of $new
Array
(
[0] => '3434','3434'
[1] => '1','2'
[2] => 'Lemon','Kidney Beans'
[3] => '20','10'
[4] => '0','0'
[5] => '3434','3434'
)
('3434','3434'), ('1','2'), ('Lemon','Kidney Beans'), ('20','10'), ('0','0'), ('3434','3434')
Error: Column count doesn't match value count at row 1
mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());
You are trying to insert something into 6 fields, so that $query string must have 6 values in it, or you get this error.
You have a lot of $query's that are 2 values. And that's not 6
It looks to me as if you are mapping your array the wrong way round. You're trying to add two records with six fields each, but what you're actually putting into the SQL statement are six records with two fields each.
This is why MySQL is complaining -- because you've told it you want to update six fields, but in each of the records you've given it, you've only specified two fields.
You need to build your array differently.
I assume that $docno1, $serialno, $acc_name, $debit and $credit will always all have the same number of array elements (it appears from your code that you are assuming this, so I'll follow you in your assumption).
In that case, you need to build your array something like this:
$multi = array();
foreach($docno1 as $key=>value) {
$multi[] = array(
$docno1[$key],
$serialno[$key], //Array for a row of fields
$acc_name[$key],
$debit[$key],
$credit[$key],
$docno1[$key])
}
Replace the block in your code where you set $multi with this, and your program should work.
Look at what print_r($multi) looks like now, and you'll see the difference.
(note, there are more efficient ways of writing your whole program than this, but I've focused on giving you a drop-in replacement for this specific bit, to help show you where you were going wrong, rather than simply rewriting the whole program for you)
Hope this helps.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the specific inserts -- for which you didn't specify a value.

Categories