0

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 ~

3
  • You've fetched a row only once - thus you're getting a one row. If you checked the documentation you would see how it's supposed to use it if you want to fetch multiple rows. Commented Mar 16, 2014 at 22:12
  • while($row = mysql_fetch_array($nats)){ echo $row['name'] } Commented Mar 16, 2014 at 22:14
  • What's the problem? What do you want to achieve? Because I can see two things that might be confusing for novice PHP/mysqli users here. Besides, this is so dangerous, ". $_POST['id']. Read about SQL Injection. Commented Mar 16, 2014 at 22:16

2 Answers 2

1

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>';
Sign up to request clarification or add additional context in comments.

7 Comments

Now it prints : Array ( [0] => 2 [id] => 2 [1] => Mucha contaminacion [name] => Mucha contaminacion )
ok, try updated code above - is that closer to what you want?
tried. No luck. Print this, missing the first one: 2 Mucha contaminacion
try $nats = mysql_query("SELECT id,name FROM reportSatus"); and see if they all come out
ok, good. Are you sure that the record "id = 2, name = Mucha contaminacion" actually has a reportId = 1?
|
0

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
}

2 Comments

Still missing values. Prints: Array ( [0] => 2 [id] => 2 [1] => Mucha contaminacion [name] => Mucha contaminacion )
It returns what you are selecting, if you loop then it will return all available records for your select

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.