Jump to content

Help Please - very simple I am sure problem with array


jipacek

Recommended Posts

Hallo there !

Can you please help me with this simple thing I can't make work or understand:

 

mysql_connect('localhost', 'jipak', 'password');

mysql_select_db('contacts');

mysql_query('SELECT name FROM contacts');

$result = mysql_query('SELECT name FROM contacts');

$row = mysql_fetch_array($result);

 

I would like to load data from sql instead of writing it manually like this:

 

$DataArr = array("Some Notes on Jeff.", "Info on Amy", "Facts on Bob.", "Some more info on Jimmy","Some gossip about Steve.");

 

<?php
mysql_connect('localhost', 'jipak', 'password');
mysql_select_db('contacts');
$result = mysql_query("SELECT `name` FROM `contacts`") OR DIE ("I wrote bad SQL code!");
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_array($result))
{
	echo "<p>{$row['name']}</p>";
}
}
else
{
echo "<p>No contacts!</p>";
}
?>

If your query returns multiple rows you'll need to use a while loop to loop through all the results. Just calling mysql_fetch_array on its own will only return the first row.

 

EDITE: Beaten to it :)

mysql_connect('localhost', 'jipak', 'password');
mysql_select_db('contacts');
mysql_query('SELECT name FROM contacts');
$result = mysql_query('SELECT name FROM contacts');

// loop through result
while($row = mysql_fetch_assoc($result))
{
    // add name to $names array
    $names[] = $row['name'];
}

// display $names array
echo '<pre>' . print_r($names, true) . '</pre>';

<?php
  mysql_connect('localhost', 'jipak', 'password');
  mysql_select_db('contacts');
  $result = mysql_query('SELECT name FROM contacts');
  $DataArr = array();
  while($row = mysql_fetch_array($result)){
    $DataArr[] = $row['name'];
  }
?>

 

God bless you this was it:

<?php

  mysql_connect('localhost', 'jipak', 'password');

  mysql_select_db('contacts');

  $result = mysql_query('SELECT name FROM contacts');

  $DataArr = array();

  while($row = mysql_fetch_array($result)){

    $DataArr[] = $row['name'];

  }

?>

 

Thank you very much.

kisses !!!

George.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.