Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.