I'm not sure if this appropriate on here since it is more of a understanding issue on my part but I''m curious to know why I receive this output:
Response id: 3 Question id: 1 Question: What is my middle name? Title: How Well Do You Know Michael
Array ( [0] => Array ( [0] => 3 [r_id] => 3 [1] => 1 [question_id] => 1 [2] => What is my middle name? [question] => What is my middle name? [3] => How Well Do You Know Michael [title] => How Well Do You Know Michael ) )
when I run this PHP script:
// Grab the response data from the database to generate the form
$query = "SELECT qr.response_id AS r_id, qr.question_id, q.question, quiz.title " .
"FROM quiz_response AS qr " .
"INNER JOIN question AS q USING (question_id) " .
"INNER JOIN quiz USING (quiz_id) " .
"WHERE qr.user_id = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query");
$questions = array();
while ($row = mysqli_fetch_array($data)) {
echo 'Response id: ' . $row['r_id'] . 'Question id: ' . $row['question_id'] . ' Question: ' . $row['question'] . ' Title: ' . $row['title'] . '<br />';
array_push($questions, $row);
}
print_r($questions);
It seems as though there are two entries for each piece of data. For example, there are two entries of the 'Response id' under index [0] and [r_id]. Both equal 3. Is it a delirious fear of mine worrying about duplicated data in my array? I'm thinking of the future when I'm doing 10's of queries at a time and whether this will affect speed or accuracy. Any input is greatly appreciated!
If you check out the documentation of mysqli_fetch_array you see the second parameter $result_type which is by default set to MYSQL_BOTH.
That means both the numerical field index (MYSQL_NUM) and the field name (MYSQL_ASSOC) are used as array-index. So if you only need the field name indices you have to use it like that:
while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
// ....
This behaviour is excpected.
From http://php.net/manual/en/mysqli-result.fetch-array.php
mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
Taken straight out of documentation:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
So changing this:
while ($row = mysqli_fetch_array($data)) {
To:
while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
This will return only string keys or alternatively, you could use mysqli_fetch_assoc
Reading http://php.net/manual/en/function.mysql-fetch-array.php, it states that the returned value of mysqli_fetch_array() (which works the same way as mysql_fetch_array()) contains both numerically indexed row data as well as field name indexed row data. If you just want field name indexed data, use mysqli_fetch_assoc().
Related
I am pulling information from a database- from two different tables. The origins of the data is a single archival document- so each row from the two tables has a unique value- line number.
So the code is as follows
//get data about the report as a whole.
$sql = "SELECT * FROM reports_list WHERE report_key ='" . $report_key . "'";
$report_data = $wpdb->get_results ($sql);
//Time to start building the file to go out.
$total_report = array();
foreach($reports_in_db as $key)
{
$total_report [$key->line_number] = $key;
}
// get subtitles/abstract
$sql = "SELECT line_number, field_text FROM subtitle_abstract_summary WHERE report_key = '" . $report_key . "'";
$abs_sums = $wpdb->get_results ($sql);
//now for a series of conditional things
if (empty($abs_sums))
{
//echo "subtitles/abstracts"
}
else
{
foreach ($abs_sums as $key)
{
$total_report [$key->line_number] = $key;
}
}
So what I expected to happen, is to create an array where the main data rows have the subtitles rows interspersed. What actually happens is that $total_report has all the main data rows, followed by all the subtitles rows. When I print_r the array, they're not in the order I expect.
for example, if the data rows are row 1-200, and the subtitle rows are 121, 161, and 181, this code produces an array that has elements 1-120, 122-160, 162-180, then 121,161 and 181 in that order.
Currently, the elements are WPDB objects. If possible, I'd like to be able to just get them in the right order. If there's also a simple way to just sort by the element number, that's okay too.
I've tried doing sort() on $total_report- but that sorted by the alphabetical value of the first field of the object..
I'm honestly just puzzled why the array doesn't have the elements in the order I thought they'd be in.
Thanks
Use ksort() to sort array by keys. And SORT_NUMERIC flag so it would sort it as numbers:
<?php
...
ksort($total_report,SORT_NUMERIC);
...
?>
I need to print/show list of comments for articles using this PHP function:
function _is_comments_($id,$type){
$db = mysqli_access::F("SELECT message FROM " . COMMENTS . " WHERE pid = ? AND type = ? AND approved = 1 ", $id, $type);
foreach($db as $row){
$commentdata['message'] = $row['message'];
}
return $commentdata;
}
In action :
$comments_list = _is_comments_('125','article');
print_r($comments_list);
In result :
Array ( [message] => this is a One comment )
But in MySQL database I have 18 comments for article id 125 and my result is false and show only One result!
how do fix This ?!
Your issue is the assignment in the loop here:
foreach($db as $row){
$commentdata['message'] = $row['message'];
}
Even if you got multiple result $rows, each iteration would overwrite the same $commentdata['message'] key. Which is why you only get to see one entry when returned from the function.
Instead you want to collect multiple entries. I would just drop the ['message'] key, and use an additive indexed array:
foreach($db as $row){
$commentdata[] = $row['message'];
}
This way your result array might contain:
Array (
[0] => this is a One comment
[1] => this is a second comment
[2] => third one
)
You need to make the message index an array.
$commentdata['message'][] = $row['message'];
In the phpMyAdmin interface I run the following SQL query:
SELECT id FROM table WHERE family = '1' AND type = 'B1'
and receive the following results:
'1', '18546269', '51534064' which are correct.
Then I wrote the following code in PHP:
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
echo '(', implode(',',$array) ,')';
But receive the following result:
(1,1) which I didn't expected.
I thought that (1,18546269,51534064) would be displayed.
Then I wrote the following code to verify what should be displayed:
print_r ($array);
and was very surprised that the values were:
Array ( [0] => 1 [id] => 1 ).
In the end I wrote:
while($array = mysql_fetch_array($result)) {
echo $array['id'],',';
}
and as expected received exactly this:
1,18546269,51534064,
which I can't use because I need a string exactly like that: (1,18546269,51534064).
In fact I 'just' need a variable that gives me the same values of the SQL query that I run in phpMyAdmin.
I'm really confused and would be great if one of you guys could help me.
Solutions with mysqli would be appreciated as well. :-)
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysqli_query($link, $query);
$ids = '';
while($row = mysqli_fetch_array($result)) $ids .= $row['id'].',';
// Filter the text a bit
$ids = rtrim($string, ',');
$ids = '('.$ids.')';
echo $ids;
You basically initiate a variable, put all the ids in it, remove the last comma, append the brackets and that's it.
As documented under mysql_fetch_array():
Return Values
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
[ deletia ]
Example #2 mysql_fetch_array() with MYSQL_NUM
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
That is to say, the function returns only one row, by default as an array consisting of both associative and numeric-indexed columns from the resultset. You want instead make multiple calls to the function, with a suitable result_type parameter (as shown above).
mysql_fetch_array fetches array of row, not array of column. That means, if you would have ID and name, the fetched array would contain on each row an id and a name.
Quite a simple modification of your code that should fix the problem would be
$i=0;
$data=array();
while($array = mysql_fetch_array($result)) {
$data[$i]=$array['id'];
$i++;
}
echo '(', implode(',',$data) ,')';
thank you for reading.
I'm having a little problem with the next sentence:
$nats = mysql_query("SELECT id,name FROM reportSatus WHERE reportId = ". $_POST['id']);
$rnat = mysql_fetch_array($nats);
With print_r($rnat) :
Array(
[0] => 1
[id] => 1
[1] => Poca contaminacion
[name] => Poca contaminacion
[2] => 1
[reportId] => 1)
But in the database with the same sentence is:
id name
1 Poca contaminacion
2 Mucha contaminacion
Any idea what can it be? Thank you in advance ~
try :
echo '<table><tr><th>id</th><th>name</th></tr>';
while ($row = mysql_fetch_assoc($nats)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td></tr>";
}
echo '</table>';
From documentation
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
That's actually the way it works, if you need more rows to be returned you will need to loop throw the records
while($rnat = mysql_fetch_array($nats))
{
//print here
}
Alright, so I'm trying to get an array of Key values from a mysql table and mysql_fetch_array() won;t seem to work properly. Code:
$x="select id from topics"
$set=mysql_query($x);
echo mysql_num_rows($set);
print_r(mysql_fetch_array($set));
$ids=mysql_fetch_array($set);
echo $ids[0];
echo $ids[1];
I've moved stuff all around but nothing seems to be changing the output:
66 //number of values in result set
Array ( [0] => 3 [id] => 3 ) //value(singular) being moved to array
4 //supposed single value of the above array
I'm really not sure what is going on here...
mysql_fetch_array brings a single row back as a PHP array, indexed by column name and by 0-based index. it DOES NOT load the whole set into a giant array, which is what you seem to be expecting.
You have to iterate over the result set in a loop, like so:
$x="select id from topics";
$set = mysql_query($x);
echo mysql_num_rows($set);
$giant_list_of_ids = array();
while ($row = mysql_fetch_array($set))
{
echo $row[0]; //or alternatively, echo $row['id'];
$giant_list_of_ids[] = $row[0];
}