here's my code, there's something wrong, because when I put this in wamp (chrome), it returns me a duplicate "published by" (for any doubts, $conex = mysql_connect('localhost', 'root') )
<?php
mysql_select_db("spectrum-solaris",$conex);
$query = mysql_query("SELECT id,name,tittle,body FROM articles ORDER BY id DESC",$conex);
$row = mysql_num_rows($query);
if($row > 0 ){
do {
?>
<div class ="tematica" >
<p>
<small>Published by <b><?= $row['name'] ?></b></small>
</p>
<p>
<big><?= $row['tittle'] ?></big>
</p>
<p>
<b><?=$row['body']?></b>
</p>
</div>
<?php
}while($row = mysql_fetch_array($query));
}
mysql_free_result($query);
mysql_close($conex);
this is the result (the blue lines are made by me on PAINT):
(http://spectrum-solaris.meximas.com/stack2.PNG)
do { } while() is not appropriate for a DB loop. On your FIRST past through the do. $row isn't going to be a DB result. It's going to be a simple integer - the number of rows in the result.
You want this instead:
$numrows = mysql_num_rows($query);
while($row = mysql_fetch_array($query)) {
...
}
Can you try this, instead of do { } while()
if($row > 0 ){
while($rowData = mysql_fetch_array($query)){
?>
<div class ="tematica" >
<p>
<small>Published by <b><?= $rowData['name'] ?></b></small>
</p>
<p>
<big><?= $rowData['tittle'] ?></big>
</p>
<p>
<b><?=$rowData['body']?></b>
</p>
</div>
<?php
}
}
mysql_free_result($query);
mysql_close($conex);
You don't fetch a row of your resultset on the first iteration... so $row doesn't contain datas on this first iteration.
You could try something like :
while ($row = mysql_fetch_assoc($query)){ // or mysql_fetch_array or ...
// ...
}
If you really want to use do{}while despite it's unsuitable for your use :
do {
$row = mysql_fetch_assoc($query); // or mysql_fetch_array or ...
// ...
} while ($row);
Related
I am fairly new to PHP and mySQL and have small issue I am busy trying to create a 4 column layout with using echo and currently I have managed to achieve this with with a mySQL database but the last column requires and additional style in the div class. With my Limited knowledge I thought of trying a count using one of the solutions I found on the forum, but I think I may be using it wrong. my idea is to echo the database array, then do a count and echo the same content block but the with additional css element in div class. Your help is greatly appreciated. if this question has been asked before please accept my apologies I am just under a lot of pressure to get it resolved.
SEE CURRENT PHP Code Below
<?php
$conn = mysqli_connect('localhost', 'root', 'password')
or die ( mysql_error());
$rs = mysqli_select_db($conn, 'database name' ) or die
( mysql_error());
$query = "SELECT * FROM database name";
$rs = mysqli_query( $conn, $query ) or die
( mysql_error());
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH))
{
$id = $row['id'];
$image = $row['image'];
$product = $row['product'];
$code = $row['code'];
$material = $row['material'];
$sizes = $row['sizes'];
echo "
<div class='percent-one-fourth'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
$i = 0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH)){
if($i++ % 4 == 0) {
echo "
<div class='percent-one-fourth column-last'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
}
mysqli_close($conn);
?>
As you're new to PHP, it's really important that you understand why your code isn't working properly. So, let's step over it and describe it in brief, simple English:
Connect to MySQL
Run a database query which has multiple rows as its response
Whilst there are more rows to go..
Output every row
Whilst there are more rows to go.. [!] Always false - we already used them all up
Output every 4th result [!] Vars like $image also aren't defined here
So, because of the way how mysqli_fetch_array works, you can hopefully see that we need to loop using it only once. This is also great for you, because it fits with the DRY (don't repeat yourself) principle.
Edit: You were also mixing MySQL API's; mysql_error is very different from mysqli_error.
So instead, during our one loop, we'll check if we're on the 4th row, and react differently. That results in something like this:
<?php
// 1. Connect to MySQL
// (this should be in a separate file and included so you don't repeat it)
$conn = mysqli_connect('localhost', 'root', 'password')
or die ( mysqli_error()); // <-- *mysqli*
$rs = mysqli_select_db($conn, 'database name' ) or die
( mysqli_error());
// 2. Run the query which has multiple rows as its response:
$query = "SELECT * FROM database name";
$rs = mysqli_query( $conn, $query ) or die
( mysqli_error());
// 3. Whilst there are more rows to go..
$i=0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH))
{
// Get easier references to various fields:
$id = $row['id'];
$image = $row['image'];
$product = $row['product'];
$code = $row['code'];
$material = $row['material'];
$sizes = $row['sizes'];
// Start outputting this row:
echo "<div class='percent-one-fourth";
// The important part! We check here in this single loop:
if($i++ % 4 == 0){
// Every 4th row - output that extra class now!
echo " column-last";
}
// Output everything else:
echo "'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
// Tidy up:
mysqli_close($conn);
?>
Your code is echoing only for the 4th column. For columns 1, 2, and 3, you need to add an else clause.
Optional: Besides instead of echoing you could close the php tag (?>) and write the html directly.
...
$i = 0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH)){
if($i++ % 4 == 0) {
echo "html for the 4th column";
}else{
echo "html for column 1, 2, and 3";
}
}
I have a table which displays information from a database. I added a column where I want to display a message according to row number displayed.
<form name="afisare1" method="POST" >
<input type="submit" name="opt1" value="OK"/>
<?php
if (isset($_POST['opt1'])) {
$loc=mysql_query("SELECT loc FROM program WHERE den='Option'");
//$loc result is a number
$sql=mysql_query("SELECT Col1, Col2
FROM date WHERE Opt_1='Option' OR Opt_2='Option'
ORDER BY Col2 DESC");
?>
<table>
<thead>
<tr>
<th>Col1</th> <th>Col2</th> <th>OK/NOT OK</th>
</tr>
</thead>
<?php
$num_rows = 0;
while ($row = mysql_fetch_assoc($sql)) {
$num_rows++;
if ($num_rows <= $loc) {
echo"<tr>
<td>".$row['Col1']."</td><td >".$row['Col2']."</td><td>OK</td>
</tr>";
break;
}
if ($num_rows > $locuri_buget) {
//here i have a problem because i don't know how to display something like this :
//echo"<tr><td>".$row['Col1']."</td><td >".$row['Col2']."</td><td>NOT OK</td></tr>";
}
}
} ?>
</table>
</form>
For example if the result of $loc=2 i want to echo for the first 2 rows OK and for extra rows i want to echo NOT OK
To retrieve loc from MySQL, your original code does it like this:
$loc = mysql_query("SELECT loc FROM program WHERE den='Option'");
But you might want to change it like this:
$loc = 0; # default value in case of error in a query
$result = mysql_query("SELECT loc FROM program WHERE den='Option'");
while($row = mysql_fetch_assoc($result)){
$loc = $row['loc'];
}
Or if you want retrieve only one record from your databse, you can also write a SQL with LIMIT like this:
$loc = 0; # default value in case of error in a query
$result = mysql_query("SELECT loc FROM program WHERE den='Option' LIMIT 1");
if($row = mysql_fetch_assoc($result)){
$loc = $row['loc'];
}
Hope this helps.
You can try with following inside while loop
if($num_rows<=$loc){
echo"<tr><td>".$row['Col1']."</td><td >".$row['Col2']."</td><td>OK</td></tr>";
}else{
echo"<tr><td>".$row['Col1']."</td><td >".$row['Col2']."</td><td>NOT OK</td></tr>";
}
$num_rows = 0;
while($row = mysql_fetch_assoc($sql)){
$num_rows++;
if($num_rows<=$loc){
echo"<tr><td>".$row['Col1']."</td><td >".$row['Col2']."</td><td>OK</td></tr>";
}else {
echo"<tr><td>".$row['Col1']."</td><td >".$row['Col2']."</td><td>OK</td></tr>";
}
}
I think your problem is with break,
break ends execution of the current for, foreach, while, do-while or switch structure.
Break
I'm trying to get this information out of the database:
$query = "SELECT * FROM station_control WHERE station_no > 0 ORDER BY station_ord";
it then says it expects parameters in these two lines:
$station_result= mysqli_query($query);
$num= mysqli_fetch_array($station_result);
this is what I want to output, basically to pull every station name from the database called station_ord and the names are under station_name:
$i=0;while ($i < $num) {
$station_name1=mysqli_result($station_result,$i,"station1_name");
$station2_name= mysqli_result($station_result, $i,"station2_name");
$station3_name= mysqli_result($station_result, $i,"station3_name");
$station4_name= mysqli_result($station_result, $i,"station4_name");
$station5_name= mysqli_result($station_result, $i,"station5_name");
echo "<b>
$station1_name $station2_name2</b> <br>
$station3_name<br>
$station1_name4_name<br>
$station5_name<hr> <br>";
$i++;
}
I haven't put in the station_name yet as im confused to where and how I configure that.
Any ideas how to help?
Not sure what you try to do, but try
<?php
$station_result= mysqli_query($query);
$records = mysqli_fetch_array($station_result);
foreach ($records as $record) :?>
<b><?php echo $record['station_name']; ?></b><br/>
<?php endforeach; ?>
ref : http://ch1.php.net/manual/en/mysqli.query.php
and http://www.php.net/manual/en/mysqli-result.fetch-array.php for examples
Something like this should work.
$station_result= mysqli_query($query);
$results= mysqli_fetch_array($station_result);
foreach ($results as $row) {
// echo whatever you want here
echo $row['station_name'];
}
I am trying to figure out why my mysqli query is not returning all the rows. For some reason it returns 3 results when there are 4 in the database. It is completely skipping the first record in the database. Here is my query.
$results = "SELECT * FROM `results` LIMIT 10";
$result = $conn->query($results);
if ($result) {
?>
<div id="tableResults">
<div class="row1 bg">Predicted Sex</div>
<div class="row2 bg">Suggested Baby Boy Name</div>
<div class="row3 bg">Suggested Baby Girl Name</div>
<div class="breaker"></div>
<?php
/* fetch object array */
$i = 0;
$count = count($result->fetch_array());
while ($row = $result->fetch_array()) {
?>
<div class="row1 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['sex']; ?></div>
<div class="row2 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['boy_name']; ?></div>
<div class="row3 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['girl_name']; ?></div>
<?php
$i++;
}
}
$conn->close();
?>
As was stated in the comments $count = count($result->fetch_array()); this will not work as expected and makes you lose one row (as it has been fetched). Instead you can use num_rows like the following
$count = $result->num_rows;
while ($row= $result->fetch_array()) {
//...
}
To go into detail, when you read the manual on fetch_array(), you'll find this part
mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both
A result row (in words: one) will be fetched any time this function is called. So currently your code is similar to:
fetch one row -> do nothing with it
while:
fetch one row -> display it
I am new to PHP , I hope someone can help me. I have a table which contains "id" , "img" , "link" and "desc" in mysql database . I want it to echo all out into something like this :
<div id="featured">
<a target='_blank' href='link'><img src='image link1' title='description'/></a>
<a target='_blank' href='link'><img src='image link2' title='description'/></a>
<a target='_blank' href='link'><img src='image link3' title='description'/></a>
<a target='_blank' href='link'><img src='image link4' title='description'/></a>
</div>
<div id="cap">
<span class='desc' id='idnumber'>Description1</span>
<span class='desc' id='idnumber'>Description2</span>
<span class='desc' id='idnumber'>Description3</span>
<span class='desc' id='idnumber'>Description4</span>
</div>
PHP CODE:
<?php
require_once "./dbconfig.php";
opendb();
$sql = "SELECT * FROM images ORDER BY id DESC";
$query = querydb($sql);
?>
<div id="featured">
<?php
while($row = mysql_fetch_array( $query )){
echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
while($row = mysql_fetch_array( $query )){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
Can WHILE being used twice or i am wrong? when i run this code , the second while loop is not working , the spans are not showing at all.
Please help.
The first loop consumes all data from mysql already, so there is nothing left in the second loop. You can store the rows data in the meanwhile however and then re-use that store.
<div id="featured">
<?php
$rows = array();
while($row = mysql_fetch_array( $query )){
$rows[] = $row;
echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
foreach($rows as $row){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
Use this before your second while loop
mysql_data_seek($query,0);
The DB reference ($query) acts as a pointer to the next unread record; when you call mysql_fetch_array(), it gets the record that is being pointed to, and moves the pointer to the next position.
Therefore, after looping through them all, the pointer will be pointing at the end of the record set, hence it returns false when you ask for the next record. Finishing the loop does not do anything else to the pointer; it remains pointing to the end of the record set.
So what you need to do is reset the pointer to the start of the data set before you can loop through it a second time.
The function to do this is mysql_data_seek();
Therefore you'd need the following line of code immediatly before your second loop:
mysql_data_seek($query, 0);
Hope that helps.
Fromt the docs for mysql_fetch_array
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
The internal data point is still at the end when you try to use your second while loop. You have done nothing to reset it.
You can move it back to the start with mysql_data_seek
You can use while twice, but see what it does:
It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.
Once mysql_fetch_array has no more rows to fetch, it will return false on every subsequent call - so your first while loop will stop looping, as the expression mysql_fetch_array( $query ) is false; and since it's the same expression in the second while, that loop will never execute (as the expression evaluates to false).
What to do: If you want to loop over the results multiple times, I'd suggest to store the result rows into an array first, then loop over them. Simplified example:
$results = Array();
while ($row = mysql_fetch_rows($query)) {
$results[] = $row;
}
foreach ($results as $row) {
echo $row['something'];
}
mysql_fetch_array will be empty because you have already fetched all of the rows from the database. You will need to reset the pointer using mysql_data_seek.
<?php
mysql_data_seek( $query, 0 );
while($row = mysql_fetch_array( $query )){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
... rest of code
With mysql_fetch_array() you are going through the results step by step, till you are at the end. Or as the PHP docs say:
Returns an array that corresponds to
the fetched row and moves the internal
data pointer ahead.
This means, you need to start from new. So, use this before your second while:
mysql_data_seek($query,0);
try this
<?php
require_once "./dbconfig.php";
opendb();
$sql = "SELECT * FROM images ORDER BY id DESC";
$query = querydb($sql);
$query2 = querydb($sql);
?>
<div id="featured">
<?php
while($row = mysql_fetch_array( $query )){
echo "<a target='_blank' href='$row[link]'><img src='$row[img]'
title='$row[desc]'/> </a>";
}
?>
</div>
<div id="cap">
<?php
while($row2 = mysql_fetch_array( $query2 )){
echo "<span class='desc' id='$row2[id]'>$row2[desc]</span>";
}
closedb();
?>
$str_res1 ='';
$str_res2 ='';
while($row = mysql_fetch_array( $query )){
$str_res1 .= " a target='_blank' href='$row[link]' img src='$row[img]' title='$row[desc]' a";
$str_res2 .= "span class='desc' id='$row[id]'> $row[desc] span>";
}
sorry i couldn't complete html tags in my answer as it disappears from post if i write "<" or "/>"
by this you can take all values in php strings and you can echo it any where you want to .
$stuff = mysql_query("SELECT * FROM tbl");
while($s = mysql_fetch_array($stuff)){
//ur code
}
// add this line
mysql_data_seek( $stuff, 0 );
while($r = mysql_fetch_array($stuff)){
//ur code
}
mysql_data_seek($query, 0); is deprecated since php 5.5 and removed from php 7.0
use mysqli_data_seek($query, 0); instead