I cant figure out why i only get 1 entry in the returning array, when the table has 4 entries in total.
My PDO code is:
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
$katarray=$stmtkat->fetch(PDO::FETCH_ASSOC);
var_dump($katarray);
The return array i get:
array(2) { ["id"]=> string(1) "1" ["kategorie"]=> string(12) "Coaching" }
The table has 4 rows, why do i get only the first row into the array?
What i am doing wrong? Obviously i am new to PDO.
Ty for your time.
You are only fetching one of the result rows produced by your query
If you use ->fetch() to get result rows one at a time you do it in a while loop like this
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
while ( $katarray=$stmtkat->fetch(PDO::FETCH_ASSOC) ) {
var_dump($katarray);
}
Or use fetchAll() to return all rows into a local array from a single call to the PDO Stmt object
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
$katarray=$stmtkat->fetchAll(PDO::FETCH_ASSOC) ) {
var_dump($katarray);
You get only one row in return because:
PDOStatement::fetch — Fetches the next row from a result set
Use fetchAll() instead to get full array() of result or use fetch() inside while() loop.
Example with fetch() and while():
while ($stmtkat->fetch(PDO::FETCH_ASSOC)) {
var_dump($katarray);
}
Example with fetchAll():
$result = $stmtkat->fetchAll(PDO::FETCH_ASSOC)
var_dup($result);
Related
I'm running this query, on two tables, and in first table, table tblhosting two condition must be met, WHERE tblhosting.server = tblservers.id AND tblhosting.domain = 'provided domain'. "provided domain is unique and here is complete query:
$result = mysql_query("SELECT hostname FROM tblhosting, tblservers WHERE tblhosting.server = tblservers.id AND tblhosting.domain = 'developer.infonet.hr'");
Query return correct result set, but two times, here is also var_dump output:
array(2) {
[0]=>
string(18) "lin-b15.infonet.hr"
["hostname"]=>
string(18) "lin-b15.infonet.hr"
}
Why is returning two same results, correct output is one, because domain is unique, is this because result is generate with mysq_fetch_array, so it is returning both associative array, and normal indexed array?
use
mysql_fetch_row() to Get a result row as an enumerated array
or
mysql_fetch_assoc() to Fetch a result row as an associative array
For Multiple record use it in while condition..
I'm using the following code to find the number of rows returned:
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM list WHERE queue = 1 ORDER BY id ASC LIMIT 0,1");
$rowcount = $results->num_rows;
echo $rowcount;
As you can see, the results are limited to 1 row, and when I run this query in SQL it returns 1 row just fine. But in PHP the $rowcount doesn't return any value at all.
Any ideas what might be wrong? I get no error.
I think you need to use count($results) since the method $wpdb->get_results returns a array of objects/arrays.
Another way to get the number of rows is to use $wpdb->num_rows. Apparently this works for
$wpdb->get_results.
From the docs (http://codex.wordpress.org/Class_Reference/wpdb), it says the following about get_results:
Generic, multiple row results can be pulled from the database with
get_results. The function returns the entire query result as an array.
Each element of this array corresponds to one row of the query result
and, like get_row, can be an object, an associative array, or a
numbered array. If no matching rows are found, or if there is a
database error, the return value will be an empty array. If your
$query string is empty, or you pass an invalid $output_type, NULL will
be returned.
How do I use the data returned by a SQL WHERE IN(x,y) statement with PHP?
$sqlquery = "SELECT * FROM schedules WHERE userid IN ('35','101','45')";
if ($test_stmt=$mysqli->prepare($sqlquery)) { //Get all data in schedule row
$test_stmt->execute(); //Execute the prepared query
$test_stmt->store_result(); //Store result
$test_stmt->fetch();
do something...
}
else {
return null;
}
}
The SQL query returns the correct three table rows, I'm just not sure how to access them with PHP.
How do I create an array to store the values the query returns? Or is there a better way to store this data to later be manipulated?
Thanks
The most common way to do this is through a loop akin to the following:
$results=array();
while($row=$test_stmt->fetch())
{
$results[]=$row;
}
This inserts the row into the results variable, which is an array. At the end of the loop, the array will contain a copy of everything the query returned.
You can also pick and choose what you do with particular columns in the results like this:
$results=array();
while($row=$test_stmt->fetch())
{
$results[]['ID']=$row['ID'];
}
This assumes there is a column called "ID" in the results though.
//$test_stmt->store_result(); //not needed
$rows = $test_stmt->fetchAll(PDO::FETCH_ASSOC); //or other fetch mode
print_r($rows); //$rows is an array of rows you can loop through
I'm getting this column in this bd
$result = mysql_query("SELECT short FROM textos");
and I'm trying to echo only one of the results based on the array it returns:
$col = mysql_fetch_assoc($result);
echo "<b>Short:</b>".$col[1]."<br/>";
apparently this $col array can't be accessed this way. How should it be done? Thanks
That has been already stated in comments above, so just a bit of explanation here.
mysql_fetch_assoc retrieves a result row for you presented as an associative array (an array where keys are field names and values are field values). Your query returns only one field (which is short), but still it doesn't make your row a single scalar value - it remains an array, only with a single element.
So you need to refer it as $row['short'], or in your sample $col['short'].
Bear in mind that query might return no results - you can learn that by checking if the returned value is not an array but scalar false instead, e.g.
if ($col === false) {
echo 'Error occured<br/>';
} else {
echo "<b>Short:</b>".$col['short']."<br/>";
}
Putting LIMIT into your query like again comments suggest is a good idea as well because you wouldn't be returning potentially huge amount of data when you only need one row actually. The result would still come as a multi-dimensional array though, so that part won't change.
To access the first element use $col[0]['short'].
If you only want to output one element anyways you can add LIMIT 1 to the MySQL query.
After querying you should check if the result array is set otherwise php will throw an error saying that $col[0]['short'] is not set.
There are three mysql_fetch functions which getting rows:
mysql_fetch_array() Fetch an array with both indexes (numeric and associative)
mysql_fetch_num() Fetch an array with numeric indexes
mysql_fetch_assoc() Fetch an array with associative indexes
In your example you will get an array that is looking like this one for the function mysql_fetch_array():
array(2) {
[0]=>
string(3) "foo"
["short"]=>
string(3) "foo"
}
$statement = 'SELECT short FROM textos';
$result = mysql_result($statement);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
var_dump($row); // or echo "<b>Short:</b>".$row['short']."<br/>"; or something else you like to do with rows of the above statement
}
}
I created an Sqlite3 database with PHP:
$db = new SQLite3('mysqlitedb.db');
$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$db->exec("INSERT INTO foo (bar) VALUES ('This is another test')");
but when I try to get all the rows:
$result = $db->query('SELECT * FROM foo');
var_dump($result->fetchArray());
it only returns the first row in the db:
array(2) { [0]=> string(14) "This is a test" ["bar"]=> string(14) "This is a test" }
I'm not sure why it isn't returning all the rows.
You need to iterate over the rows. You'll only get the current row.
while($row=$result->fetchArray()){
// Do Something with $row
print_r($row);
}
The PHP Manual has a good example on the page
fetchArray() fetches only the first row of results. If you want to fetch additional rows, make additional calls to fetchArray (perhaps in a loop).
Requesting an answer where all results are returned in one array. It seems wasteful to be able to get all results in one object, have them split by array entry, then having to put them back into one array.