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];
}
Related
im new in field of manipulating databases so i have a problem.
So after making a query to select all values from a table row with something like :
while($row = $result->fetch_assoc()) { }
For example if table has names in it we would get :
John
Bob
Steve
Mark
If we put these results in a form of a link or a button, is there any way to get their value?
i tried something like :
if (isset($_POST['result_button'])) {
$value =$row['name'];
}
I tried this when i put all the results from query in to a form of button, but that only pulls the last value from table row.
I tried putting results into array like :
$result= array();
$result[]=$row['name'];
echo $result[2];
I don't fully understand how arrays works so might have done something wrong there but from what i tried this works only if i put echo$result[0];
Ok, firstly:
$row = $result->fetch_assoc()
This does not work how you're expecting it to. What this is basically saying, is that for each returned value (from the MySQL query), store in $row for this iteration of the while loop.
So, in you're example, $row will first be John, then Bob, then Steve and finally Mark. They are not all stored in the variable at the same time. Bob overwrites John, etc.
I'm going to skip your second bit of code, as it's clear you do not have an understanding of arrays.
Arrays
There is plenty of material about arrays on the web. I'm not sure why you had to post the question here, however...
To define an array:
$my_array = array();
An array with values:
$my_array = array(
"bar",
"foo"
);
Assign variables to an array:
$my_array = array();
$my_array[0] = "Help" // $my_array[0] now contains "Help"
$my_array[1] = "Me"; // $my_array[0] now contains "Me"
So, taking you're final example:
$result= array();
$result[]=$row['name'];
echo $result[2];
You haven't stored anything in the 2nd element of the array.
This would be more appropriate:
$result= array();
$result[0] = $row['name'];
echo $result[0]; // This would print what was stored in $row['name']
I have a database in MySQL and I'm using this query to select certain rows from it using PHP:
$q = "SELECT Number, Body
FROM boxes
WHERE Number BETWEEN '1' AND '4' ORDER BY Number ASC";
Then calling the query and initiating arrays:
$r = $mysqli->query($q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$array = array();
$content = array();
Then attempting to sort the results into an associative array where the 'number' is the key and the 'body' is the value.
while ($row = mysqli_fetch_assoc($r)) {
$array = array(
$content[$row['Number']] = $row['Body']
);
This works fine except it will not store the first value. This is the result of print_r($content);, missing the first row.
Array ( [2] => This is entry two [3] => This is entry three [4] => This is entry four )
I have tried running the SQL query within PHPMyAdmin and it returns all four rows as I would expect.
Does anyone have any ideas what I'm doing wrong?
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
You are getting first returned row by this line. You have to remove it and it will work properly.
mysqli_fetch_array and mysqli_fetch_assoc returning NEXT row on every call.
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
}
What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}
I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);