while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$row = mysql_fetch_array($result, MYSQL_ASSOC) //it's not increase ?
}
i want increase two time in each loop?
for
<table>
<td>**1 times**</td><td>**1 times**</td>
</table>
I think the documentation is very clear. http://hu.php.net/manual/en/function.mysql-fetch-array.php or http://hu.php.net/manual/en/function.mysql-fetch-assoc.php.
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
You don't need that.
If you want to print your data formatted in 2 columns, select it all into array and then use that array for the formatted output.
one of possible solutions
<?php
//collect data into array
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
//and here goes template part
?>
<html>
<? $data = array_chunk($data, 2) ?>
<table>
<? foreach ($data as $chunk): ?>
<tr>
<? foreach ($chunk as $row): ?>
<td><?=$row['name']?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
it WILL increase the pointer by 1 step...
therefore:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// logic here
}
will perform the loop and logic
Why not do something like this:
$max_row = 100;//mysql_num_rows($result);
for($idx = 0; $idx < $max_row; $idx+=2){
if (!mysql_data_seek($result, $i)) {
echo "Cannot seek to row $i: " . mysql_error() . "\n";
continue;
}
if (!($row = mysql_fetch_assoc($result))) {
continue;
}
//do what you want to do here...
}
if you have 10 records, it will echo row 0, 2, 4, 6, 8.
<?php
$counter=0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if ($counter % 2)
{
echo '<table><tr>'; // start table
}
echo '<td>' . $row['foo'] . '</td>'; // echo result
if (!$counter % 2)
{
echo "</tr></table>"; // end table
}
$counter++;
}
?>
Maybe you want mysql_data_seek?
Related
I need this code to give me a little different output.
<?php
$conn=mysqli_connect("localhost","root","","");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function print_tableA ($conn, $id) {
$sql = "SELECT Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8 FROM mytable1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='$id'>";
while($row = $result->fetch_assoc()) {
echo '<tr><td>' . join('</td><td>', $row) . "</td></tr>\n" ;
}
echo "</table>";
}
}
$result = $conn->query("SELECT Date from mytable2");
while ($row = $result->fetch_assoc()) {
print_tableA ($conn, $row['Date']);
}
?>
Currently it prints the output in this format: `
<tr>
<td>2</td>
....
</tr>`
I need it to be printed in this format:
<tr>
<td val="2">2</td>
....
</tr>
so basically the data from the mysql should also be repeated as a td attribute. I hope this is simple, and I'd be grateful if someone can show me the change that I need to make to get this output. Thanks.
Replace while loop with this one:
while($row = $result->fetch_assoc()) {
$data = array_reduce($row, function($carry, $value) {
$carry[] = "<td val='{$value}'>{$value}</td>";
return $carry;
}, []);
echo '<tr>' . implode('', $data) . "</tr>\n" ;
}
will output:
<tr><td val='10'>10</td><td val='11'>11</td></tr>
A sendbox example can be found here.
PHP Manual for array_reduce function.
You need to iterate through the row values and echo the td as you want them:
while($row = $result->fetch_assoc()) {
echo '<tr>';
// Let's iterate through all the columns
foreach ($row as $value) {
echo "<td val='$value'>$value</td>";
}
echo "</tr>\n";
}
Just as a note: val isn't a valid attribute in for a td-element.
Hi I'm attempting to display data retrieved from a mysql table horizontally in an html table using php. The code below works well except for the fact that it leaves out the first record (starts at the second record) in my database. I'm sure it has something to do with the counter but I can't seem to figure out how to get it to stop doing this. If anyone can point out my error I'd really appreciate it!
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query)
or die(mysql_error());
$row = mysql_fetch_array($result);
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
$i = 0;
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
if ($i==0) {
echo "<tr>\n";
}
echo "\t<td align=\center\">$first_name</td>\n";
$i++;
if ($i == $items) {
echo "</tr>\n";
$i = 0;
}
}//end while loop
if ($i > 0) {
for (;$i < $items; $i++) {
echo "<td> </td>\n";
}
echo '</tr>';
}//end ($i>0) if
echo '</table>';
}else {
echo 'no records found';
}
try and remove the 1st
$row = mysql_fetch_array($result);
you are calling it twice, that's why it skips 1 row in your while loop
try this simpler.
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
echo "<tr>";
for ($i=0 ; $i <= $items ;$i++) {
echo "<td align='center'>".$first_name."</td>";
}
}//end while loop
echo "</tr>";
echo '</table>';
}else{ echo 'no records found'; }
I have run into this issue before. Try the do while loop instead. Example
do {
// code
} while($row = mysql_fetch_array($result)); //end while loop
$row = mysql_fetch_array($result);
1) remove this line of code from ur scripts
2) only use while loop code instead.
I have a table named members with 3 rows. The following code attempts to display all the rows in the members table. It displays the 1'st record 3 times instead of displaying each record once.
<?php
$con = new mysqli("localhost", "root", "jce123", "profile");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
$keysarray = array_keys($array);
$valuearray = array_values($array);
for ($i=0; $i < $num; $i++) {
for($j = 0; $j < count($array); $j++) {
echo "<table>";
echo "<tr><td>".$keysarray[$j].": </td><td>".$valuearray[$j]."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
mysqli_close($con);
?>
I've updated this per suggestions:
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
while ($row = mysqli_fetch_assoc($res)) {
foreach($array as $key => $value){
echo "<table>";
echo "<tr><td>".$key.": </td><td>".$value."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
That's because, your $num = 3, count($array) = 3 and the outer for loop has no bearing on inner for loop.
Where you have $array = mysqli_fetch_assoc($res);, you will only receive one row from your database. You need something like:
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
}
Any basic tutorial will tell you this. Even the PHP docs provide an example.
you can use do something like this..
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
e.g
echo $row['id'];
echo $row['name'];
etc
}
try this... this peace of code is not tested but just to give you an idea...
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
echo "<table>";
echo '<tr><td> id = "'.$row['id'].'":
</td><td> name = "'.$row['name'].'"</td></tr>";
echo "</table>";
}
Ok I have this code:
<?
$name=$_POST['name'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE id='$name'");
$ss = ""
while($row = mysql_fetch_array($result))
{
$ss .= "<div style='border:1px solid red; float:left; width:100px;'><img src="Images/media'.$row['name'].'" />";
$ss .= "<p>".$row['title']."</p>";
$ss .= "<p>".$row['description']."</p>";
$ss .= "<a href='".$row['link']."'>".$row['link']."</a></div>";
}
mysql_close($con);
?>
<? echo $ss; ?>
Now, I want to organize the display, therefore, I want the record to be set by 3 but the only problem where im stuck is I dont know how to make it to display in by set of 3. Im open for a suggestion, please help me. Thank you.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
mysql_connect("localhost","root","");
mysql_select_db("juliver");
$name = mysql_real_escape_string($_POST['name']);
$data = sqlArr("SELECT * FROM items WHERE id='$name'");
$data = array_chunk($data,3);
include 'template.tpl.php';
a template
<table border='1'>
<? foreach ($data as $row): ?>
<tr>
<? foreach ($row as $cell): ?>
<td><?=$cell['id']?><?=$cell['title']?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
In while loop you can put the condition to know when it executes 3 times then it would go automatically on other line. have a look
int $a=0;
while($row = mysql_fetch_array($result))
{
if($a%3==0){
this will executes only if when the no of record dividable by 3. means 3,6,9,12..
do this..
}else {
do this..
}
$a++;
}
Is this OK ?
$i = 0;
while ($row = mysql_fetch_array($result))
{
$resultset[] = $row;
$columns[] = mysql_fetch_field($result, $i);
}
Then when trying to print
<tr><th><?php echo $columns[0] ?></th><th><?php echo $columns[1] ?></th></tr>
I got an error
Catchable fatal error: Object of class stdClass could not be converted to string
Try the mysql_fetch_field function.
For example:
<?php
$dbLink = mysql_connect('localhost', 'usr', 'pwd');
mysql_select_db('test', $dbLink);
$sql = "SELECT * FROM cartable";
$result = mysql_query($sql) or die(mysql_error());
// Print the column names as the headers of a table
echo "<table><tr>";
for($i = 0; $i < mysql_num_fields($result); $i++) {
$field_info = mysql_fetch_field($result, $i);
echo "<th>{$field_info->name}</th>";
}
// Print the data
while($row = mysql_fetch_row($result)) {
echo "<tr>";
foreach($row as $_column) {
echo "<td>{$_column}</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Use mysql_fetch_assoc to get only an associative array and retrieve the column names with the first iteration:
$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
}
$resultset[] = $row;
}
Now you can print the head of your table with the first iteration as well:
echo '<table>';
$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th>'.implode('</th><th>', $columns).'</th></tr>';
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>', $rows).'</td></tr>';
}
echo '</table>';
You want to look at
mysql_fetch_assoc
Which gives each row as an associative key => value pair where the key is the column name.
Documentation here
Here is a more modern solution with ...i:
$db_link = #mysqli_connect($server, $user, $pass, $db) or die("Connection failed");
$spalten = ['pc_name', 'pc_type', 'pc_snr', 'pc_bj', 'mo_port_1', 'mo_snr_1', 'mo_bj_1', 'mo_port_2', 'mo_snr_2', 'mo_bj_2'];
$abfrage = "SELECT " . implode(',', $spalten) . " FROM hardware order by pc_name";
$liste = mysqli_query($db_link, $abfrage);
$spalten = mysqli_num_fields($liste);
while ($werte[] = mysqli_fetch_array($liste, MYSQLI_ASSOC)) {}
<table class="display" id="table" style="width:100%">
<thead>
<tr>
<?php
for ($i = 0; $i < $spalten; $i++) {
$feldname[$i] = mysqli_fetch_field_direct($liste, $i)->name;
echo '<th>' . ucfirst($feldname[$i]) . '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < mysqli_num_rows($liste); $i++) {
?>
<tr>
<?php for ($j = 0; $j < $spalten; $j++) {
?>
<td><?php
echo $werte[$i][$feldname[$j]];
?>
</td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
Though it's deprecated and no longer in PHP 7 you can avoid having to use an object by using the function mysql_field_name instead which returns a string.