I am selecting data from mySQL database with fetchAll:
$sql = "SELECT id, dateTime, fileName, path, size FROM files WHERE project = ?";
$q = $pdo->prepare($sql);
$q->execute([$id]);
$result = $q->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
The array looks like this:
array(2) {
["10002E41F35560F492298F50D14B03A1"]=>
array(5) {
["dateTime"]=>
string(19) "2016-10-12 19:46:25"
["fileName"]=>
string(10) "monkey.jpg"
["path"]=>
string(59) "Volumes/KFS18050001/18050001/elephant/cat/monkey/monkey.jpg"
["size"]=>
string(7) "8650752"
}
["10008A76CEE6BEEEB8000891094A2931"]=>
array(5) {
["dateTime"]=>
string(19) "2016-10-12 14:39:43"
["fileName"]=>
string(9) "horse.jpg"
["path"]=>
string(51) "Volumes/KFS18050001/18050001/elephant/cat/horse.jpg"
["size"]=>
string(7) "8306688"
}
}
But when I have more then 500.000 entries in my database then this is too much for the system. The array is not created. It is loading very long and then I get a blank page. The I tried to use fetch instead of fetchAll:
$sql = "SELECT id, dateTime, fileName, path, size FROM files WHERE project = ?";
$q = $pdo->prepare($sql);
$q->execute([$id]);
$result = $q->fetch(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
With fetch, my system can handle the 500.000 entries. But now I do not get the result I need:
array(6) {
["id"]=>
string(32) "10002E41F35560F492298F50D14B03A1"
["dateTime"]=>
string(19) "2016-10-12 19:46:25"
["fileName"]=>
string(10) "monkey.jpg"
["path"]=>
string(59) "Volumes/KFS18050001/18050001/elephant/cat/monkey/monkey.jpg"
["size"]=>
string(7) "8650752"
}
horse.jpg is just not displayed. And the id is now not the key of the array.
Is there any way to retrieve the same result then with fetchAll by using just fetch or is there a way to not overwhelm the system with fetchAll and a lot of entries?
Since I highly doubt you need to load 500,000 images at once, I suggest you try the following.
What I would do is continue using fetchall() but only select the results from the database that you currently need. If you need to load all the images, lets say if you are creating an instagram-type program, I suggest you dynamically load the images and as you scroll down the page, query the database every few hundred images.
You can do this with limit in mysql:
SELECT ....query here.... LIMIT 0,100
and once your user has scrolled down say, 80 images, query the database again with the following:
SELECT ....query here.... LIMIT 100,199
This way you will not overload either the database or the client's system with too many results.
Related
I have converted one of my websites to use PDO database queries. All the queries are working perfectly except one and I have spent all day trying to solve this problem and nothing is working for me so as a last resort I am asking for some advice here.
This is the function I am having the problem with
public function getTransactions($iProfileId)
{
$rStmt = Db::getInstance()->prepare('SELECT * FROM' . Db::prefix(DbTableName::GIFT_TX) .
'WHERE profileId = :profileId ' .
'ORDER BY createDate ASC, txId ASC');
$rStmt->bindValue(':profileId', $iProfileId, \PDO::PARAM_INT);
$rStmt->execute();
$this->getTxs = $rStmt->fetch(\PDO::FETCH_OBJ);
Db::free($rStmt);
return $this->getTxs;
}
It returns a single row even though there are many others and as an object
object(stdClass)#47 (8) { ["txId"]=> string(1) "8" ["profileId"]=> string(3) "861" ["type"]=> string(6) "credit" ["credits"]=> string(2) "25" ["createDate"]=> string(19) "2020-06-26 10:48:55" ["isDelete"]=> string(1) "0" ["price"]=> string(4) "0.05" ["merchant"]=> string(6) "PayPal" }
I need this to be returned as an array and to get all the rows with profileId = :profileId
I have tried everything I can find online and have had no success at all.
Try this code
$this->getTxs = $rStmt->fetchAll(PDO::FETCH_ASSOC);
If in doubt, check out the URL below:
https://www.php.net/manual/en/pdostatement.fetchall.php
I'm writing a Shopware plugin, and I have the following code to build an SQL query:
$queryBuilder = $this->container->get('dbal_connection')->createQueryBuilder();
$queryBuilder->select('a.articleID', 'v.optionID', 'v.value')
->from('s_filter_articles', 'a')
->leftJoin('a', 's_filter_values', 'v', 'a.valueID = v.id')
->where('a.articleID IN (:ids)')
->andWhere('v.optionID IN (3, 8)')
->orderBy('a.articleID, v.optionID')
->setParameter(':ids', $relatedIds);
The built SQL string is the following, according to $queryBuilder->getSql():
SELECT a.articleID, v.optionID, v.value
FROM s_filter_articles a LEFT JOIN s_filter_values v ON a.valueID = v.id
WHERE (a.articleID IN (:ids)) AND (v.optionID IN (3, 8))
ORDER BY a.articleID, v.optionID ASC
When I replace ":ids" with "1,2,3,4,5" and execute the query, all rows get returned as expected. (I made sure that $relatedIds is "1,2,3,4,5", too.)
When I execute the query in PHP (via $queryBuilder->execute()->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC)), only results for the first ID (1) are returned. var_dump($result)shows the following:
array(1) { [1]=> array(2) { [0]=> array(2) { ["optionID"]=> string(1) "3" ["value"]=> string(13) "Schwarz Kombi" } [1]=> array(2) { ["optionID"]=> string(1) "8" ["value"]=> string(7) "Schwarz" } } }
Why is this not returning results for other IDs (2,3,4,5)?
I think you need a real array in
->setParameter(':ids', $relatedIds);
for example
$relatedIds = [1,2,3,4,5]
The problem was that $relatedIds is a string, so setParameter(':ids', $relatedIds) inserted it with quotes
WHERE a.articleID IN ('1,2,3,4,5')
instead of
WHERE a.articleID IN (1,2,3,4,5)
I need to pass an array instead of a string to achieve what I want.
Additionally, it is necessary to pass a type to setParameter:
setParameter(':ids', $relatedIds, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
I am very new to PHP and MySQL and am trying to get data from a MySQL table and print it. I make a call to the database and it works great. I am able to read info. out. but there are duplicates in the data.
So far I have:
<?php
/// Make a MySQL Connection
mysql_connect("localhost", "loop", "XXX") or die(mysql_error());
mysql_select_db("loop") or die(mysql_error());
// Retrieve all the data from the "profile" table
$result = mysql_query("SELECT * FROM profile")
or die(mysql_error());
//print out info.
while ($row = mysql_fetch_array($result)) {
echo("<pre>");
var_dump($row);
echo("</pre>");
}
?>
This produces:
array(1) {
[0]=>
array(14) {
[0]=>
string(1) "1"
["id"]=>
string(1) "1"
[1]=>
string(13) "test#test.com"
["email"]=>
string(13) "test#test.com"
[2]=>
string(8) "passcode"
["pass"]=>
string(8) "passcode"
[3]=>
string(4) "John"
["nameFirst"]=>
string(4) "John"
[4]=>
string(5) "Smith"
["nameLast"]=>
string(5) "Smith"
[5]=>
string(8) "face.jpg"
["pic"]=>
string(8) "face.jpg"
[6]=>
string(16) "Some dummy text."
["bio"]=>
string(16) "Some dummy text."
}
}
Why does it have duplicate elements? I checked the database and it is OK. Can someone explain what I am missing?
You can pass a second parameter to mysql_fetch_array function to tell it whether to return an associative array (hashmap - of columns to row values) or a regular array of row elements. By default it will return both.
http://php.net/manual/en/function.mysql-fetch-array.php
There are also dedicated functions to fetch row values as an array and hashmap:
mysql_fetch_row()
mysql_fetch_assoc()
This is because mysql_fetch_array returns both numeric and associative array by default check php manual mysql_fetch_array
Please try to use mysql_fetch_assoc instead of mysql_fetch_array because mysql_fetch_array was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
but if you still want to use this than this will help
try to pass a second parameter mysql_fetch_array($result, MYSQL_ASSOC) or mysql_fetch_array($result, MYSQL_NUM)
I'm creating a sortable power ranking list for a madden nfl league. IF you want to see it its at
http://www.stephenjesse.com/projects/powerrankings/index.php
The problem I'm getting when I'm trying to calculate the change from the last saved ranking the query used to get the last ranking returns null sometimes causing the change to be wrong because it thinks the old rankings is 0 when its not. Here is a basic snippet of the for loop
foreach($order as $team)
{
$query="SELECT * FROM powerrankings WHERE team='$team'";
echo "query to select team:".$query."\n\n";
$result=mysqli_query($db,$query) or die(mysqli_error($db));
$selectedTeam=$result->fetch_assoc();
$oldRank=intval($selectedTeam['ranking']);
$change=$oldRank-$rank;
I'm not really sure what wrong, I check the apache error log, I've tried outputting mysqli_errer() and I've checked the mysql.log error log and nothing shows up.I've tried sleeping 5 seconds between queries incase the queries are being fired to quickly but that doesn't work. Its only some times. Here is a sample of the debug output I have on the page
query to select team:SELECT * FROM powerrankings WHERE team='Panthers'
team:Panthers
old rank:5
new rank:1
array(7) {
["ranking"]=>
string(1) "5"
["team"]=>
string(8) "Panthers"
["comment"]=>
string(0) ""
["change"]=>
string(1) "0"
["record"]=>
string(5) "0-0-0"
["low"]=>
string(1) "5"
["high"]=>
string(1) "5"
}
array dump:
query to select team:SELECT * FROM powerrankings WHERE team='Bills'
team:Bills
old rank:0
new rank:2
NULL
array dump:
query to select team:SELECT * FROM powerrankings WHERE team='Falcons'
team:Falcons
old rank:0
new rank:3
NULL
array dump:
query to select team:SELECT * FROM powerrankings WHERE team='Cardinals'
team:Cardinals
old rank:0
new rank:4
NULL
array dump:
query to select team:SELECT * FROM powerrankings WHERE team='Ravens'
team:Ravens
old rank:0
new rank:5
NULL
array dump:
query to select team:SELECT * FROM powerrankings WHERE team='Bears'
team:Bears
old rank:6
new rank:6
array(7) {
["ranking"]=>
string(1) "6"
["team"]=>
string(5) "Bears"
["comment"]=>
string(0) ""
["change"]=>
string(1) "0"
["record"]=>
string(5) "0-0-0"
["low"]=>
string(1) "6"
["high"]=>
string(1) "6"
}
a you can see sometimes it works and sometimes it doesn't. Any help would be greatly appreciated.
NULL means that there are no matching rows for you query: no team named "Bills".
Do a check in your code for NULL before updating ranking
if ($selected_team = $result->fetch_assoc()) {
// update ranking
}
I'm working on an import feature from one database to another and thought I'd try out the built in Mysqli features.
I have opened two connections, one for each database, and am looping through the old one (to get the existing users) and running checks on the new one before choosing whether or not to insert the data.
Now I'm not sure if I'm misusing the prepared statements feature or what as I am having trouble getting the correct results. A simple test case is:
$oldDB = new Mysqli(HOST, USER, PASS, 'oldDB');
$newDB = new Mysqli(HOST, USER, PASS, 'newDB');
/*
* Prepared statments
*/
$searchUserStmt = $newDB->prepare('SELECT user_id FROM members WHERE user_id=?');
$searchUserStmt->bind_param('i', $old_user_id);
$searchUserStmt->bind_result($user_id);
/**
* Loop through users
*/
$result = $oldDB->query('SELECT * FROM member_profile LIMIT 10');
while($row = $result->fetch_assoc())
{
var_dump($row['user_id']);
// Check if user is already in DB
$old_user_id = $row['user_id'];
$searchUserStmt->execute();
$searchUserStmt->fetch();
$searchUserStmt->reset();
var_dump($user_id);
}
My first query on $oldDB runs fine and loops through the users however when I look up the user_id in the $newDB with the prepared statement it only returns the user_id of the first result.
Here's a sample of the output I get:
string(1) "1"
int(1)
string(2) "31"
int(1)
string(2) "26"
int(1)
string(3) "105"
int(1)
string(2) "34"
int(1)
string(3) "119"
int(1)
string(2) "36"
int(1)
string(2) "37"
int(1)
string(2) "38"
int(1)
string(2) "39"
int(1)
Does anyone have any idea what I'm doing wrong? I've been through the Mysqli docs but didn't find anything that helped me.
Ok I found the problem, things were working correctly however it appears that the variable used in mysqli_stmt::bind_result() doesn't get updated unless there is a row found. In my tests only the first user was found which resulted in the 1 being returned everytime.
mysqli_stmt::fetch() will return NULL when no results are found so I simply had to modify my code slightly like so:
while($row = $result->fetch_assoc())
{
var_dump($row['user_id']);
// Check if user is already in DB
$old_user_id = $row['user_id'];
$searchUserStmt->execute();
if($searchUserStmt->fetch() === NULL)
{
// Insert user here
}
$searchUserStmt->reset();
}