MYSQL PDO fetch multiple rows from fetchAll not working - php

How to get all the posts in wordpress using single query.
I have tried below using fetchAll(), but its not working.
It just displays RESUlT as many times there are total posts.
Code:
UPDATED Helper file:
$posttypevalue = Mage::helper('wordpress')->getPostMetaData();
var_dump($posttypevalue); //gives NULL
Template file
public function getPostMetaData()
{
try{
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('new_db');
//$query = 'SELECT meta_value FROM ' . $resource->getTableName('wp_postmeta'). ' WHERE post_id = '.$postID.' and meta_key = "type"';
echo 'vardumping results'; //Even this line is not displaying
$query = 'SELECT wp_posts.*, wp_postmeta.meta_value
FROM wp_posts ,wp_postmeta
WHERE wp_posts.ID =wp_postmeta.post_id
AND wp_postmeta.meta_key="type"
AND wp_posts.post_status="publish"';
$results = $readConnection->fetchAll($query);
//$postdata = array();
//foreach($results as $value){
//var_dump($value); //gives empty
//$postdata[]= $value['post_title'];
//}
}catch (Exception $e) {
return true;
}
}
DB structure is as:
Output:
For the 1st query which is commented:
$query = 'SELECT meta_value FROM ' . $resource->getTableName('wp_postmeta'). ' WHERE post_id = '.$postID.' and meta_key = "type"'
vardumping results
1 displayed 5 times
For the query i am using currently:
Output for var_dump($values):
Empty page with header and footer.
Even the echo above the line $query doesnt display.
It very weird!!

You can do a var_dump($value) to see the content.
I think you should use $postdata[] = $value['post_title'];.
The field names of the results don't contain the table name.

Related

PHP MySQLi to PDO?

I don't know why my code doesn't return true, the while loop works fine, but there's a problem.
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '?%' ");
$PDO_result->bindParam(1, $pismenka[$i]);
$PDO_result->execute();
Here when I var_dump() $PDO_result I get one item in array so the following while loop should work:
while($row = $PDO_result->fetch(PDO::FETCH_ASSOC))
but it doesn't.
Working MySQLi:
$result = mysqli_query($connect_to_db, "SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '$pismenka[$i]%' ");
while($row = mysqli_fetch_array($result))
The most simple solution would be to change $pdo->fetch(PDO::FETCH_ASSOC) to $pdo->fetchAll(PDO::FETCH_ASSOC)
fetchAll returns ALL rows in the requested query, while fetch only gets 1 row (the first)
Example:
<?php
try {
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE ?");
//Execute by inserting an array:
if (!$PDO_result->execute([$pismenka[$i] . "%" ])) { //Added ."%"
die('Error!');
}
//Fetch rows:
$rows = $PDO_result->fetchAll(PDO::FETCH_ASSOC);
//Go trough each row:
foreach ($rows as $row) {
//Do something
}
//Catch exceptions thrown by PDO
} catch (PDOException $ex) {
print_r($ex);
}

SQL Count Not Working From Inside of PHP Code

I have the weirdest issue going on. COUNT() is not working from inside my PHP code, but it is working in the SQL input space in the PHPMyAdmin database. For example if I use the following query:
SELECT COUNT(*) FROM posts WHERE category = "coding"
It will return the correct results from the SQL input in the PHPmyadmin part, but from the PHP code it will always return 1. Here is the code I am using for the PHP:
function numberofposts($category, $connection) {
$query = "SELECT COUNT(*) FROM posts WHERE category = :category";
$params = array(':category' => $category);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
return $result;
}
echo "Number of Posts: " . numberofposts("art", $connection);
What it is doing is in the first code at the top it will return the correct results, but in the PHP code it is always returning 1. Is there a problem with me PHP? Please just post if you do not understand what I am asking, or if you would like more information.
You are doing a select and you execute the statement, but you are not fetching the row with the results.
You probably want something like:
function numberofposts($category, $connection) {
$query = "SELECT COUNT(*) as cnt FROM posts WHERE category = :category";
^^^ for easy access
$params = array(':category' => $category);
try{
$stmt = $connection->prepare($query);
$stmt->execute($params);
$row = $stmt->fetch();
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
return $row['cnt'];
// if you don't alias the column you can do:
// return $row[0];
}

Display more than one row from SQL SELECT

I want to display all of the rows shown in the picture where CID = 1.
Here is my PHP code with SQL:
`
$contractCount = 1;
$sql = "SELECT categories.categoryID
FROM categories
LEFT JOIN link
ON categories.categoryID = link.categoryID
WHERE link.CID = '$contractCount'";
$res = $con->query($sql);
if (!$res) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = mysqli_fetch_array($res)) {
echo $row['categoryID'];
}
Here is an image showing the table in PHPMyAdmin called categories.
So I need output as ITSM, Mar and HrAd but I am only getting ITSM and not the rest.
EDIT 1: The LEFT JOIN makes no difference here, the link table has no bearing on the SELECT statement
EDIT 2: I have solved the problem, my mistake was that I had the table names the wrong way round in the SQL query.
You need to use the function mysql_fetch_row, this will fetch a row and move the pointer to the next one.
while ($row = mysqli_fetch_row($res)) {
echo $row['categoryID'];
}

Get columns names only from multiple tables by a join query

$sql = "SELECT * FROM
fbr.*, c.sample, ci.dob, ci.country, ci.sex
FROM `finalBloodReport` fbr ,`clients` c, `client_info` ci
WHERE fbr.sampleSerialNo = (CONCAT(c.resellerSerialId,'-',c.kitSerialNo) )
AND c.client_id = ci.id";
This is my query it works fine and gives the desired output,But since i am showing data in table i also want to get columns name only for this query to show them as table header .
I tried Something like this , but result is null.
$sql = "SHOW COLUMNS
fbr.*, c.sample, ci.dob, ci.country, ci.sex
FROM `finalBloodReport` fbr ,`clients` c, `client_info` ci
WHERE fbr.sampleSerialNo = (CONCAT(c.resellerSerialId,'-',c.kitSerialNo) )
AND c.client_id = ci.id";
Can anyone help ? I am not so good with mysql ; (
You need to retrieve column information after query is executed. This can be done by using mysqli_fetch_field()
You code should look like following
$result = mysqli_query($sql);
while($field = mysqli_fetch_field($result)) {
print $field->name . "\t";
}
while ($row = mysqli_fetch_row($result) {
print_r($row);
}

Php stuck because to long load on mysqli query in php function, how to fix?

i'm using a php function to get dome mysql data from other mysql host than my webserver.
Function:
public function theMysqli($build){ // $build is given by othe code (no usedata)
$mysqli = new mysqli($server, $user, $password, $database);
$catid = array( /* +/- 40 id's */ ); //data is $catid = configs::songcats();
$type = array( /* +/- 15 captical letters */ ); //data is $type = configs::songtype();
$limit = 20;
$lstart = $_post['page'];
if($lstart == ''){
$lstart = 0;
}
else{
$lstart = $lstart * $limit;
}
$sletter = $_POST['letter'];
$search = $sletter.'%';
$catquery = "SELECT songid FROM category WHERE catID IN('".implode("', '", $catid)."')";
if ($db = $mysqli->query($catquery)){
while($row = $db->fetch_array()){
$idsong[] = $row;
}
$db->close();
}
foreach($idsong as $gt){
$songid[] = $gt['songid'];
}
// songid is a array over the 30000 values
$countquery = "SELECT id FROM songlist WHERE songtype IN('".implode("', '", $type)."') AND id IN('".implode("', '", $songid)."') AND songname LIKE '".$search."'";
if ($db = $mysqli->query($countquery)){
$countr = $db->num_rows;
$db->close();
}
$pages = ceil($countr / $limit);
$songquery = "SELECT id, songname, artist, copyright, duration FROM songlist WHERE songtype IN('".implode("', '", $type)."') AND id IN('".implode("', '", $songid)."') AND songname LIKE '".$search."' ORDER BY songname ASC LIMIT $lstart, $limit";
if ($db = $mysqli->query($songquery)){
while($row2 = $db->fetch_array()){
$result[] = $row2;
}
$db->close();
}
if($built == 'counter'){
$final == $pages;
}
else if($build == 'gresult'){
$final == $result;
}
return $final;
}
Now my problem is the load time he need for this script it will be to long. Even when i set php.ini so that execute may be 300sec he will stuck by loading the page. Now i know you can get data grom mutiple mysql tables by one query but i can't find any solution to do that in combination with php implode function.
Total rows i must get by $_POST['letter'] M is +/- 1200; (web radio mp3 database)
Can someone help me to fix this function so i get no timeout's anymore.
Thanks
The problem here is that you're fetching a list from the database, and then sending that list back as part of a query. You should really be doing most of this stuff in SQL, using either JOIN or nested queries. This will make your program much faster.
First, create a table for all of your catids and types. Your catquery should then be:
SELECT songid
FROM category
WHERE catID IN (
SELECT id
FROM catids
)
Use the same sort of pattern to join your queries together. It looks like you can cut down most of your code here to just one SQL query. You'll save a ton of time and memory by not having to send all that data back and forth between your program and the database.
Some reading material for you:
SQL Joins: http://beginner-sql-tutorial.com/sql-joins.htm
SQL Subquery: http://beginner-sql-tutorial.com/sql-subquery.htm

Categories