This is my code
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
is there any way to extract title,text,date from $result and put them into 3 dimensional array?
What about
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$array = array();
$i = 0;
while( $row = mysql_fetch_assoc( $result ) {
$array[$i] = array();
// i'm just guessing at what sort of array you want
$array[$i][$row['title'] = array( 'text' => $row['text'], 'date' => $row['date'] );
$i++;
}
I'd be interested to know what the ... you need a three-dimensional array for but ok:
$dim = array();
$result = mysql_query(...);
while ( $row = mysql_fetch_assoc($result) )
// Whatever you want to save in that particular bucket,
// I'll be using the result set
$dim[$row['title']][$row['text']][$row['date']] = $row;
Strange, ...
If we are already guessing, here is mine:
$results = array();
while(($row = mysql_fetch_assoc($result))) {
$results[] = $row;
}
which will create an array like this:
array(array('title' => 'foo',
'text' => 'bar',
'date' => 'baz'),
//...
)
I think what you're after is actually a two-dimensional array (in which the second dimension has three elements). (Correct me if I'm wrong.)
One of the comments under the documentation of mysql_fetch_array has an answer to this:
(Disclamer: This code is unnecessarily verbose. I prefer not changing it though as I have copied it from the above web-page. For improvements, I refer to the comments.)
<?php
function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
$i=0;
$keys=array_keys(mysql_fetch_array($result, $numass));
mysql_data_seek($result, 0);
while ($row = mysql_fetch_array($result, $numass)) {
foreach ($keys as $speckey) {
$got[$i][$speckey]=$row[$speckey];
}
$i++;
}
return $got;
}
?>
You should then be able to use this function as
<?
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$arr = mysql_fetch_rowsarr($result);
$row_2_title = $arr[2]['title'];
?>
Related
I'm trying to make an array with the result of a mysql query but instead I'm making an array of objects.
Have unsuccessfully tried to convert the array of objects into an array, is that the best approach?
echo json_decode(json_encode($iconsArray), true); // didnt work
This is my query
function listIcons(){
global $link;
$queryAssets = "SELECT DISTINCT icon_1,icon_2,icon_3,icon_4 FROM icons";
$resultqueryAssets = mysqli_query($link, $queryAssets) or
die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($resultqueryAssets)) {
$iconsArray[] = $row;
}
$allIcons = json_encode($iconsArray);
echo $allIcons;
return array($allIcons);
}
allIcons outout is
$allIcons = [
0:{icon_1: "01_a", icon_2: "01_b", icon_3: "01_c", icon_4: "01_d"}
1{icon_1: "02_a", icon_2: "02_b", icon_3: "02_c", icon_4: "02_d"}
]
And the output that I need but cant achieve
$allIcons = [
0:"01_a"
1:"02_a"
2:"01_b"
3:"02_b"
4:"03_a"
5:"02_b"
...
]
Most likely this is the easiest thing to do:
<?php
// ....
$queryAssets = "SELECT DISTINCT icon_1,icon_2,icon_3,icon_4 FROM icons";
$resultqueryAssets = mysqli_query($link, $queryAssets) or
die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($resultqueryAssets)) {
foreach ($row as $icon) {
$icons[] = $icon;
}
}
var_dump($icons);
An alternative without an additional loop would be such thing:
<?php
// ....
$queryAssets = "SELECT DISTINCT icon_1,icon_2,icon_3,icon_4 FROM icons";
$resultqueryAssets = mysqli_query($link, $queryAssets) or
die(mysqli_error($link));
$icons = [];
while ($row = mysqli_fetch_assoc($resultqueryAssets)) {
$icons = array_merge($icons, array_values($row));
}
var_dump($icons);
Actually things get easier if you don't fetch an associative array at all:
<?php
// ....
$queryAssets = "SELECT DISTINCT icon_1,icon_2,icon_3,icon_4 FROM icons";
$resultqueryAssets = mysqli_query($link, $queryAssets) or
die(mysqli_error($link));
$icons = [];
while ($row = mysqli_fetch_row($resultqueryAssets)) {
$icons = array_merge($icons, $row);
}
var_dump($icons);
I did not run these code snippets, just typed them down. I hope there is no silly typo in them...
I have a method of creating JSON into an array that looks like this:
[{"date":"","name":"","image":"","genre":"","info":"","videocode":""},{...},{...}]
I first tried getting the data from a html page (not the database) like this:
$arr = array();
$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);
$videocode = linkExtractor6($html);
for ($i=0; $i<count($images); $i++) {
$arr[] = array("date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i], "info" => $info[$i], "videocode" => $videocode[$i]);
}
echo json_encode($arr);
Where each linkExtractor looks a bit like this - where it grabs all the text within a class videocode.
function linkExtractor6($html){
$doc = new DOMDocument();
$last = libxml_use_internal_errors(TRUE);
$doc->loadHTML($html);
libxml_use_internal_errors($last);
$xp = new DOMXPath($doc);
$result = array();
foreach ($xp->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' videocode ')]") as $node)
$result[] = trim($node->textContent); // Just push the result here, don't assign it to a key (as that's why you're overwriting)
// Now return the array, rather than extracting keys from it
return $result;
}
I now want to do this instead with a database.
So I have tried to replace each linkExtractor with this - and obviously the connection:
function linkExtractor6($html){
$genre = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
foreach ($genre as $node)
$result[] = $node;
return $result;
}
But I am getting the error:
Invalid argument supplied for foreach()
Avoid redundancy and run a single SELECT
function create_json_db($con){
$result = mysqli_query($con,"SELECT date, name, image, genre, info, videocode
FROM entries
ORDER BY date DESC");
$items= array();
while ($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
return $items ;
}
Try to use this. More info in the official PHP documentation:
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$items = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$items[] = $row;
}
return $items;
}
First, you are not iterating through your results via something like mysqli_fetch_array. So here is the function with mysqli_fetch_array in place. But there is a much larger issue. Read on.
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Okay, with that done, it still won’t work. Why? Look at your function. Specifically this line:
$result = mysqli_query($con,"SELECT genre
But where is $con coming from? Without a database connection mysqli_query will not work at all. So if you somehow have $con set outside your function, you need to pass it into your function like this:
function linkExtractor6($con, $html){
So your full function would be:
function linkExtractor6($con, $html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Remember, functions are self-contained & isolated from whatever happens outside of them unless you explicitly pass data into them.
I have the following code:
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$result = $mysqli->query($query);
$rows = resultToArray($result);
//print_r($rows); // Array of rows
$result->free();
Brings back the following (only an excerpt):
Array ( [0] => Array ( [q17] => [COUNT(q17)] => 7 ) [1] => Array ( [q17] => Admin & Clerical [COUNT(q17)] => 118 )......etc.
What I am struggling with is how to then return the data, basically, what I need is some code to pull out the data as follows:
WHERE Array = Admin & Clerical BRING BACK THE COUNT(q17) number
How do I search through the array, normally, I'd use something like:
if($rows['q17']==$q[$i]){echo$rows['COUNT(q17)'];}
But this doesn't work - I assume because there are two sets of data within each part of the array? Not sure how to deal with this.
You can achieve this by using MYSQL itself, by using HAVING clause instead of WHERE.
To do this rewrite your query like this.
$query = 'SELECT q17, COUNT(q17) as qcount FROM tresults GROUP BY q17 HAVING q17="Admin & Clerical" ';
echo $row[0]['qcount']; //return 118
if you still want to it with PHP after getting the result from the database, it's how it done:
function get_q17_count($rows, $q17){
foreach ($rows as $onerow) {
if($onerow['q17'] == $q17){
return $onerow['COUNT(q17)'];
}
}
}
function resultToArray($results) {
$rows = array();
while($row = $results->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$querys = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$results = $mysqli->query($querys);
$rows = resultToArray($results);
//print_r($rows); // Array of rows
$results->free();
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['q17'] === $id) {
return $val['COUNT(q17)'];
}
}
return null;
}
Called the function using:
$id = searchForId($q[$i], $rows);echo " (".$id.")";
If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it
I am trying to store the data from my sql database into an array. Currently I have this:
$query = mysql_query("SELECT * FROM `InspEmail` WHERE `Company` LIKE '$company'");
while($row = mysql_fetch_array($query))
{
$inspector = $row['name'];
}
The problem is that I have 8 rows of data. I need to store each 8 names from that database into an array. When I try this:
$inspector = array($row['name']);
It doesn't work.
If you want to store all of the names in an array, you need to define the array outside the scope of the while loop and append to it. Like this:
$nameArray = array();
while($row = mysql_fetch_array($query)) {
// Append to the array
$nameArray[] = $row['name'];
}
What you want is:
$inspector[] = $row['name'];
This will store all 8 names in an array similar to:
array(
[0] => name1
[1] => name2
[2] => name3
)
Lots of good answers. But if you do this often, you might want to write a little function:
mysql_field_array($sql, $fieldname)
{
$res = mysql_query($sql);
$a = array();
while($row = mysql_fetch_array($res))
{
$a[] = $row[$fieldname];
}
mysql_free_result($res);
return $a;
}
Replace this line...
$inspector = $row['name'];
...with this:
$inspector [] = $row['name'];
After that, the inspector array contains all the names.
$query = mysql_query("SELECT * FROM `InspEmail` WHERE `Company` LIKE '$company'");
$data = array();
while($row = mysql_fetch_array($query))
{
$inspector[] = $row;
}
for($i=0;$i<mysql_num_rows($row);$i++)
{
$data = $inspector[$i];
}
return $data;
Check it...