PHP : Select from Database - php

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
}

Related

PHP json_encode returning single row only

So I have an associative array $_SESSION['cart_items']) This is the current output when I print_r($_SESSION['cart_items']):
Array
(
[3] => 23
[5] => 5
[4] => 1
)
In the output above, the first one for example [3]=>23 where [3] is the id and 23 is the quantity I entered from a form:
My current data:
Note that in the image above, the quantity column is different from the quantity I'm entering from a form.
So far this is the code I've tried:
$statement = $conn->query("SELECT id, name, price, quantity FROM product WHERE id IN (".implode(',',$_SESSION['cart_items']).")");
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
print json_encode($data);
And this is the output:
[{"id":"5","name":"ballpen","price":"23","quantity":"13"}]
As you can see it works, though I only get a single row which should be three.
Is there something wrong with my query?
You show that the array keys in the session array match the ids in the database. implode() implodes/joins the values in the array. So you need to implode the keys:
implode(',', array_keys($_SESSION['cart_items']))
Or flip the array:
implode(',', array_flip($_SESSION['cart_items']))

preg_match_all array insert into mysql database loop not working properly

I'm trying to preg_match_all the first 12 digit number found in a mysql field, and insert that number in another field, looping through all results from the Select statement.
I have the following, which puts only the first result it finds in all the fields, so every field3 gets the same 12 digit number inserted, that 12 digit number being from the lowest unique ID field found by the Select statement. Any help with this would be greatly appreciated.
<?php
$query = mysql_query("SELECT * FROM `dbase`.`table` WHERE field1 IS NOT NULL AND field3 IS NULL");
$regexp ='/[0-9]{12}/';
while ($row = mysql_fetch_assoc($query)){
$result=($row["field1"]);
preg_match_all($regexp,$result,$matches,PREG_PATTERN_ORDER);
foreach($matches[0] as $match => $where){
$id=($row["field2"]);
$sql="UPDATE `dbase `.`table ` set field3 = $where WHERE field2 = '$id'";
mysql_query($sql);
}
}
?>
I added
print_r( $matches );
and the output was an array with one result, the number being place in all the fields:
Array
(
[0] => Array
(
[0] => 290970571788
)
)
The curly bracket change fixed the print_r output to show the the list of 12 digit numbers in this format (only first two are shown):
Array
(
[0] => Array
(
[0] => 151104658286
)
)
Array
(
[0] => Array
(
[0] => 271249191324
)
)
Thanks for that.
Utilizing the answers and suggestions given here, I've edited the code to show the final working version. The last big issue was getting the 2nd select statement to use the array result, properly looping and inserting each value in the proper row. Also cleaned up the 1st select statement and changed from preg_set_order to preg_pattern_order.
It shouldn't be
{while ($row = mysql_fetch_assoc($query))
}
but
while ($row = mysql_fetch_assoc($query)) {
}
You don't want to create code block with while statement but you want to provide code block for it.
And also you're using same WHERE condition in SELECT and UPDATE so it'll update all selected rows with same value (all will match that condition).

mysql_fetch_array() not working properly, missing most values

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];
}

php 2d array ... store mysql results in 2d array

I have a sql statement that returns a number of records each having 10 attributes. How can i get the data and put it into a 2D array. Currently Im doing this :
while($row1 = mysql_fetch_array($result1))
{
echo $row1[0][1]; //There is an error here
}
Is $row1 a 2D array? (It should be because Im getting n*m results). If $row1 is a 2d array then shouldn't i be able to access $row[0][1]?
mysql_fetch array returns a 1-D array, combined indexed + keyed values of one single row of data from your query results. e.g. doing
SELECT field1, field2, field3 FROM sometable
and doing a mysql_fetch_array on the result will give you an array that looks like:
$row1 = array(
0 => 'value of field1',
1 => 'value of field2',
2 => 'value of field3',
'field1' => 'value of field1'
'field2' => 'value of field2',
'field3' => 'value of field3'
)
If you want to address the entire result set as a single array, you'll have to fetch each row and add it to that array first:
$data = array();
while($row1 = mysql_fetch_array($result)) {
$data[] = $row1;
}
Which would let you do $data[0][1] (2nd field [1] of 1st record [0])
From the docs:
Fetch a result row as an associative array, a numeric array, or both
If mysql_fetch_array is recovering 1 row of data, what do you expect the second dimension to be?
First off you need to verify what sort of array you are getting, then you can understand why your keys aren't valid. Try using print_r or var_dump to examine $row1.
$row1 holds only one record at a time so it is a regular one-dimension array.
If your query returns
a b c
d e f
In the first iteration of the while loop, row1 holds a b c and in the second iteration, it holds d e f, both single-dimension arrays.
$row1 is a 1-dimensional array (a single record), in your case, holding 10 values.
As the code loops through the while statement, $row1 represents each record.
refer to the documentation here: http://ca.php.net/manual/en/function.mysql-fetch-array.php

Duplicated data entries in PHP array

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().

Categories