Reputation: 26450
Alright, so I have a database, each with an ID, a name and a textvalue.
I wish to be able to print each of a specific row individually. When I use
$result = mysql_query("SELECT * FROM mytable", $db);
$row = mysql_fetch_array($result);
echo $row['text'];
I am only able to print the first row, as it doesn't select any specifics. The problem is, I'm not sure how to use the WHERE ID='X', as I want the first one to print the first column, the second to print the second column and so forth (there are a total of 13 lines). I want to echo them on different places on the page, so just calling everything at once is not what I'm looking for.
The way things are now, I'll have to use the code above for each time I want to print it, and manually edit the WHERE ID='1' on the first print, the second to WHERE ID='2' and so on, which is rather a pain in the ass.
Any suggestions is appreciated.
Upvotes: 1
Views: 149
Reputation: 853
This is how to iterate through all records.
$result = mysql_query("SELECT text FROM mytable", $db);
while ( $row = mysql_fetch_array($result) ) {
echo $row['text'];
}
Upvotes: 2
Reputation: 3372
Here's an example using a more object-oriented approach:
1) setup a PDO object like this:
$dbhost = '127.0.0.1';
$dbuser = 'yourDbUsername';
$dbpass = 'yourDbPassword';
$dbname = 'databaseName';
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$dbAdapter = new PDO($dsn,$dbuser,$dbpass);
$dbAdapter->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbAdapter->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
2) use PDO objects to run queries and fetch result sets:
$sql = 'SELECT * FROM mytable';
$statementObject = $dbAdapter->query($sql);
$resultSet = $statementObject->fetchAll();
3) iterate over the resulting array:
foreach($resultSet as $row){
echo $row['text'] . "<br />";
}
Upvotes: 2
Reputation: 7791
$i = 1;
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $i . ' - ' . $row[0] . '<br/>';
$i++
}
If you want 4 variables with the text to use in differents part of your code then use:
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
$var1 = mysql_fetch_array($result, MYSQL_NUM);
echo $var1[0];
$var2 = mysql_fetch_array($result, MYSQL_NUM);
echo $var2[0];
$var3 = mysql_fetch_array($result, MYSQL_NUM);
echo $var3[0];
$var4 = mysql_fetch_array($result, MYSQL_NUM);
echo $var4[0];
Upvotes: 1
Reputation: 8659
Keep calling mysql_fetch_array
until it returns null:
while($row = mysql_fetch_array($result ))
{
echo $row['text'] . '<br/>';
}
This is shown in the documentation, which also will tell you this:
Warning This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
Upvotes: 4