I'm trying to make a table of iframes (2 per row) and I query everything, but whenever it prints, everything is on a row of it's own even though I only tell every second one to. I can't figure out why this is happening:
<div id="main" style="width:1000px;">
<?php
$query = "SELECT * FROM scripts";
mysql_connect("localhost", "root", "");
mysql_select_db("scriptsearch");
$results = mysql_query($query);
$num = mysql_num_rows($results);
mysql_close();
?>
<table border="0">
<?php
for($i = 0; $i <= $num; $i++){
if($i % 2 == 0) //is this the second one? if so, make a new row
echo '<tr>';
else{
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php }if($i % 2 == 0) echo '</tr>';/*end the row*/ } ?>
</table>
</div>`
Edit: I've tried Krynble's solution, but no matter how I modify it, it still doesn't show up how I expect.
There's an error in your loop.
Try this:
<?php
for($i = 0; $i <= $num; $i++){
if($i % 2 == 0) //is this the second one? if so, make a new row
echo '<tr>';
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php if($i % 2 == 1) echo '</tr>';/*end the row*/ } ?>
<?php if($i % 2 == 1) //close last row in case we haven't done it yet.
echo '</tr>';?>
You should print the iframe unconditionally, not inside an else. Besides, the closing </tr> should be printed when $i is odd.
Other people have commented on the php/html part, let me focus on the query part:
Don't do this:
$query = "SELECT * FROM scripts"; (1) select all ?
mysql_connect("localhost", "root", ""); (3) don't connect as root!
mysql_select_db("scriptsearch");
$results = mysql_query($query); (4) no check for errors?
$num = mysql_num_rows($results); (2) when you only want 1 count?
Do this instead:
$query = "SELECT count(*) as rowcount FROM scripts";
mysql_connect("localhost", "user1", "password");
mysql_select_db("scriptsearch");
if ($results = mysql_query($query)) {
$row = mysql_fetch_row($results);
$num = $row['rowcount'];
} else { echo "error....." }
You don't have an opening <tr> tag in your table. You need to have a table row before you can put data in it.
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 some HTML in a variable that I'd like to loop 4 time per row. I am making a couple of queries first. In one I get the number of rows and store it in a variable. The second, I am looking to fetch the associated data that I will need to display.
$results = $dbCon->query("SELECT * FROM table WHERE status = '1' ORDER BY id DESC LIMIT $start, $limit");
$total = mysqli_num_rows($results);
$res = $dbCon->query($results);
$data = $res->fetch_assoc();
$link = $data['link'];
$title = $data['title'];
$image = $data['image'];
$imgAlt = $data['imgAlt'];
Third, I store what I want to display in a variable. The HTML I plan on displaying looks something like this
$html = printf("<div style=\"text-align:center; max-width:270px; white-space:normal; word-wrap:break-word; border-left:1em solid transparent; border-right:1em solid transparent; text-overflow: ellipsis; float:left;\">
<a href=\"%s\">
<img style=\"width:270px; height:232px; margin-bottom:40px; border-radius:45px; -moz-border-radius:45px; -webkit-border-radius:45px; box-shadow:0px 0px 3px #fff; -moz-box-shadow:0px 0px 3px #fff; -webkit-box-shadow:0px 0px 3px #fff;\" src=\"images/recentshoots/%s\" alt=\"%s\" />
<p>%s</p> <br /></a>
</div>", $link, $image, $imgAlt, $title);
Next, I would like to loop the 20 items per page in 4 items per row. This is where I am having some trouble. My issue is that the number of characters in the $title are always different so the layout breaks apart. At first a tried a simple way using css and php to do a str_pad() but it doesn't seem to work right with empty spaces. I always get some containers that are taller than others which distorts my row. So I did some research in this platform to model after someone else example.
I m having some trouble with what I found because the examples I've seen have information missing that I need to understand how to modify my own. I have seen it done with foreach and while loops. Can someone help me find a way to understand this better?
How can I loop the data retrieved and make sure that only 4 per row exist in a page of 20 items? Thank you so much for your help. I started with something like this
$startingPoint = 1;
echo "<div class=\"row\">";
foreach($startingPoint < 4){ //this foreach is not even starting the right way, how can I fix this?
echo $html;
}
Can I use a foreach? or a while loop? or do-while?
which one is the best solution and the fastest or most efficient way to go? The shorter the code the better.
Foreach loops are used for array datatypes whilst a while loop can be used for booleans and more.
What you're looking for is a for loop, this allows your to set a counter and each time the loop is ran it adds to a counter. Once the expression is met, it ends the loop.
for($i = 1; $i == 4; $i++)
{
echo 'Loop ' . $i . ': This will loop 4 times';
}
However, you could fix your foreach by using this snippet:
$startingPoint = [1,2,3,4];
foreach($startingPoint as $start)
{
echo $html;
}
Since there are 4 items inside the array, the loop will continue 4 times.
Your SQL is returning more than one row of data thus creating $data to become multidimensional, your loop therefore may not work how its written, you could try this:
for($i = 1; $i >= $limit; $i++)
{
print_f(<!-- html here -->, $data[$i]['column']);
}
You can try this code. Full pagination and view:
Example: index.php
<?php
//get page id for pagination and limit query
$limit = 4;
if(isset($_GET["page"]))
$page = intval($_GET["page"]);
else
$page = 1;
$total = $limit * $page;
$start = $total - $limit;
//GEt data from database. I have used mysqli for testing purpose.
$conn=mysqli_connect("localhost","root","","dbname");
$result = mysqli_query($conn, "SELECT * FROM table WHERE status = '1' ORDER BY id DESC LIMIT $start, $limit");
$total = mysqli_num_rows($result);
?>
<!--Your html code what you want-->
<table>
<tr>
<th>Title</th>
<th>Image</th>
<th>Link</th>
</tr>
<!--loop inside html-->
<?php while($data = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $data['title']; ?></td>
<td><img src="<?php echo $data['image']; ?>" alt="<?php echo $data['imgAlt']; ?>"> </td>
<td>Link</td>
</tr>
<?php } ?>
</table>
<?php
/**======== Pagination Url generate=============*/
$totalPages = ceil($total/$limit);
if($page <=1 ){
" <span style='font-weight: bold;'> < Prev </span> ";
}else{
$j = $page - 1;
echo " <a href='index.php?page=$j'>Prev</a> ";
}
for($i=1; $i <= $totalPages; $i++){
if($i<>$page){
echo " <a href='index.php?page=$i'>$i</a> ";
}else{
echo " <span style='font-weight: bold;'>$i</span> ";
}
}
if($page == $totalPages ){
echo " <span style='font-weight: bold;'>Next ></span> ";
}else{
$j = $page + 1;
echo " <a href='index.php?page=$j'>Next</a></span> ";
}
?>
Hey guys I need your help, I have this table
and I want to shows like this FIDDLE, really I don't know how to do this because sometimes just exist two columns(prov_name ) and sometimes exist more that two rows please help me if you can !
Hope you understand me. Thanks so much !
In this way I can be able to select data from Joomla.
$db =& JFactory::getDBO();
$query = 'SELECT prov_name FROM provprices where CA_id = '.$CA_id;
$db->setQuery($query);
$result = $db->loadObjectList();
$prov_name = $result[0];
echo $prov_name->prov_name;
First off, in order for your data to be presented like that obviously it must be grouped accordingly.
The first row is, the prov_name's, so you can use GROUP BY or you cal also do it in PHP. Based of the sample data, it should have from 1 to 6.
Then the second row is just a simple unitval and totval according to how many prov_name's.
Third is the and the rest is the grouping of the values. See Example:
$db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME;charset=utf8', 'USERNAME', 'PASSWORD');
$data = array();
$results = $db->query("SELECT * from YOUR_TABLE_NAME");
while($row = $results->fetch(PDO::FETCH_ASSOC)) {
$data[$row['prov_name']][] = $row;
}
$keys = array_keys($data);
$size = count($keys);
$vals = array();
// grouping:
// if there are six (cam1 to cam6)
// then group them by cam1, ... to cam6, then repeat until theres no more left
while(count($data) > 0) {
foreach($keys as $key) {
if(!empty($data[$key])) {
$vals[] = array_shift($data[$key]);
} else {
unset($data[$key]); // remove them if empty
}
}
}
$vals = array_chunk($vals, $size); // split them by how many prov_names
?>
<table border="1" cellpadding="10">
<!-- PROV NAMES -->
<tr><?php for($x = 1; $x <= $size; $x++): ?>
<th colspan="2"><?php echo "prov_name $x"; ?></th>
<?php endfor; ?></tr>
<!-- unitval totvals -->
<tr><?php for($x = 1; $x <= $size; $x++): ?>
<td>unitval</td><td>totval</td>
<?php endfor; ?></tr>
<!-- the grouped values -->
<?php foreach($vals as $val): ?>
<tr>
<?php foreach($val as $v): ?>
<td><?php echo $v['unitval']; ?></td>
<td><?php echo $v['totval']; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
I think you must do this first,
try looping to show prov_name in horizontal,
and then you fetch again in query with
"SELECT * FROM table_test where prov_name = '$prov_name'"
in Variable $prov_name you must have a value with CAM2 or CAM3 .etc
sorry just a logic :)
CODE :
$result= mysql_query ("SELECT COUNT(post_id) AS postCounter FROM headlines WHERE user_id= '$_SESSION[user_id]' ");
$numrows = mysql_num_rows ($result);
if ($numrows!=0){
while ($row = mysql_fetch_array ($result))
$postCounter = $row['postCounter'];
for ($i=1; $i<=$postCounter; $i++){
echo "$i";
}
}
Now, what I want to know is "How could I use for-loop to echo div's depending on the COUNT result?"
So if $postCounter above was "4" I need to display 4 divs for it .
In your for loop, echo a DIV instead of just echoing the number.
for ($i = 1; $i <= $postCounter; $i++) {
echo "<div>$i</div>";
}
An other way you can do by FOREACH to embed html into php
<ul>
<?php foreach($postcounter as $post) { ?>
<li><?php echo $post; ?></li>
<?php } ?>
</ul>
Hope this help
I have a mysql table, one of its columns called parking space has a number in it. However, for some records the 'parking space'-column is empty. Now, I want to call just this column in a page table where the column heads are numbered from 1 - 200 (first column: 1; second column: 2;....) So, if there is the value '12' in the 'parking space'-column, then this shall show up in column '12' and so on, and if there is no entry for a number then the column in the page table shall be left empty. How can I associate the numbers in 'parking space' with that page table?
...
<?php
$pagetable=array('1','2','3','4','5','6');//...until 200
foreach($pagetable as $value){
?>
<table border="1px" cellspacing="1" cellpadding="1">
<tr>
<th>
<?php echo $value ?>
</th>
</tr>
<?php
}
include("dbinfo.inc.php");
include_once("config.php");
$result = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results = mysql_num_rows($result);
if ($results > 0){
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"id");
$park=mysql_result($result,$i,"park");
?>
<tr>
<td style="background-color:;">
<?php echo $park; ?>
<br>
<?php if($park!=''){ ?>
<?php echo $id; ?>
<?php
}
?>
</td>
</tr>
<?php
$i++;
}
}
?>
...
There are two ways, you can do this.
Create all 200 rows on the database table and query it. This will omit almost all of the headache to get what you want.
Do a for loop from 1 to 200 and compare the active item if it exists on the mysql results. For this you require an continuous numeric entry in the database to identify each columns individually.
What I mean is? Column 1 in the should have corresponding record indicating 1 somewhere in its record.
Here is an example of this:
$result = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results = mysql_num_rows($result);
if ($results > 0) {
$num=mysql_numrows($result);
$rows = array();
while($row = mysql_fetch_row($result)) {
$rows[$row['id']] = $row;
});
//Now process it
}
Try this:
<?php
include("dbinfo.inc.php");
include_once("config.php");
$spaces = range(1, 200);
$results = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results_count = mysql_num_rows($result);
if ($results_count > 0) {
for ($i = 0; $i < $results_count; $i++) {
$parks[] = mysql_result($results, $i, "park");
}
}
?>
<table>
<tr>
<?php foreach ($spaces as $space): ?>
<td><?php echo $space ?></td>
<?php end foreach ?>
</tr>
<tr>
<?php foreach ($parks as $park): ?>
<td><?php if ($park > 0) { echo "$space"; } else { echo " "; } ?></td>
<?php end foreach ?>
</tr>
</table>
Start with this and tell me what you get.
Ok, I got it changed a little. Now it ahows me all from 1-200 and it shows the parking spaces values, but these values are not associated with the numbers. it looks to me like it puts them according to the id, for example in my table the customer on parking space 165 has the id 4 and therefore it doesnt put 165 to 165 but 165 to 4
<?php
include("dbinfo.inc.php");
include_once("config.php");
$spaces = range(1, 200);
$results = mysql_query("SELECT * FROM contacts");
$results_count = mysql_num_rows($results);
if ($results_count > 0) {
for ($i = 0; $i < $results_count; $i++) {
$parks[] = mysql_result($results, $i, "park");
}
}
?>
<table>
<tr>
<?php foreach ($spaces as $space){ ?>
<td><?php echo $space; ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach ($parks as $park){ ?>
<td><?php if ($park!='') { echo $park.'<br>';} else { echo " "; } ?></td>
<?php }?>
</tr>
</table>