views:

14

answers:

2

Hello everyone,

I am kind of stumped on the idea of echoing a list of strings from a mysql server. How would the process go? The format I want it to be is like this:

Name 1
Name 2
Name 3
Name 4

However each new name is in a new cell, and I don't know how to gather every single name from the mysql server. PHP is a very new language for me so please go easy :)

+1  A: 

Query the table and then loop through the resulting array, this example is assuming the column name is "name"

$query = “SELECT * FROM table”;
$showresult = mysql_query($query);

while($results_array = mysql_fetch_assoc($showresult))
{
  echo "Name ".$results_array["name"];
}
Pete Herbert Penito
Is there any way I can get the full list of the array with all the names, instead of having to echo it one by one?
Kevin
I'm not quite sure what you mean, you could print_r($results_array) inside the while loop that would print everything inside each row. The while loop is necessary because it iterates through each row, otherwise $results_array would only grab the values of the first row. :) This can be kinda confusing at first, please don't hesitate to keep asking questions, thats how people learn
Pete Herbert Penito
A: 

There are at least three extension modules that provide access to a MySQL server: the old php-mysql module, the MySQL improved module and PDO with its MyQL driver. Pete has given you an example of the "old" mysql module. Let me show you an example using pdo and (server-side) prepared statements:

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
setupTestdata($pdo);

$stmt = $pdo->prepare('SELECT foo FROM soTest WHERE id<?');
$stmt->execute( array(3) );
while( false!==($row=$stmt->fetch(PDO::FETCH_ASSOC)) ) {
  echo $row['foo'], "\n";
}

echo "same statement again, different parameter:\n";
$stmt->execute( array(5) );
while( false!==($row=$stmt->fetch(PDO::FETCH_ASSOC)) ) {
  echo $row['foo'], "\n";
}

function setupTestdata($pdo) {
  $pdo->query('CREATE TEMPORARY TABLE soTest (id int auto_increment, foo varchar(16), primary key(id))');
  $pdo->query("INSERT INTO soTest (foo) VALUES ('nameA'), ('nameB'), ('nameC'), ('nameD'), ('nameE')");
}

prints

nameA
nameB
same statement again, different parameter:
nameA
nameB
nameC
nameD
VolkerK