Issue with bootstrap grid and mysql response - php

I have an issue with bootstrap and creating a 4 column responsive grid from a mysql response.
The problem is that if the second mysql query has a variable number of results, it brakes the grid.
Here is my code (where the first query has 9 results and the second query has a variable number of results):
<?php
$a = "SELECT * FROM $table_users ORDER BY username";
$result = mysql_query($a);
?>
<div class="container">
<div class="row">
<?php while ($row = mysql_fetch_array($result)) {?>
<div class="col-xs-3" style="background-color:aqua;">
<?php echo $row['username'];
$b = "SELECT * FROM $table_presents WHERE bought_for='$row[username]' OR bought_for='' ORDER BY id";
$result_presents = mysql_query($b) or die(mysql_error());
while ($row_presents = mysql_fetch_array($result_presents)) {
?>
<div style="background-color:red;">
Hello world!
</div>
<?php }?>
</div>
<?php }?>
</div>
</div>
which gives me this:
enter image description here
instead of this (obviously with many 'Hello world'):
enter image description here
Any help greatly appreciated!

Bootstrap doesn't claim to do any kind of elegant bin-packing on panels with different sizes. You could do some programming or css work to make all your panels the same size.
If that doesn't work for your application, you're going to need a layout library that does bin-packing so these panels of different sizes align properly.
There are a few such libraries available as jQuery plugins.

In this, $row[username] is wrong as it should be $row['username'].
$b = "SELECT * FROM $table_presents WHERE bought_for='$row[username]' OR bought_for='' ORDER BY id";
BTW, I changed your code bit. Please Try this.
<?php
$a = "SELECT * FROM $table_users ORDER BY username";
$result = mysql_query($a);
?>
<div class="container">
<div class="row">
<?php while ($row = mysql_fetch_array($result))
{
$username=$row['username'];
?>
<div class="col-xs-3" style="background-color:aqua;">
<?php echo $username;
$b = "SELECT * FROM $table_presents WHERE bought_for='$username' OR bought_for='' ORDER BY id";
$result_presents = mysql_query($b) or die(mysql_error());
while ($row_presents = mysql_fetch_array($result_presents)) {
?>
<div style="background-color:red;">
Hello world!
</div>
<?php }?>
</div>
<?php }?>
</div>
</div>
[NOTE: Users can inject your SQL commands. Use prepared statements and parameterized queries. For more info, click Prevent SQL Injections

Related

PHP gallery album

i am writing a php script that retrieves images from a database and shows them on page inside an album , each album contains several images...
here is an example for the code below :
$sql = "SELECT * FROM tbl_album where status='process' ORDER BY albumid DESC LIMIT $start_from, 12";
<?php
$rs_result = mysql_query ($sql,$con);
while ($row = mysql_fetch_assoc($rs_result))
{
$aid=$row['albumid'];
$aimage=$row['image'];
$aname=$row['name'];
$astatus=$row['status'];
echo '<div class="col-lg-4 col-md-6 col-sm-6 agile_gallery_grid">';
echo '<div class="hover ehover14">';
?>
<?php
echo"<a href='#details?d=$aid' onclick='showfunction()'>";
echo "<img src='admin/acatch/$aimage' class='img-responsive' alt='$aname' width='200' height='200' data-picture_id='$aid'>";
echo'</a>';
}
?>
this code shows all the albums contained in the database ,
but what i want to do is that when i click on the album cover , i want to display the images inside it on the same page , but i am not able to pass the album id to another php script on the same page to do this,
please if anyone can help
thank u in advance
Have a look at the following code:
<?php
$sql = "SELECT * FROM tbl_album where status='process' ORDER BY albumid DESC LIMIT $start_from, 12";
$rs_result = mysql_query($sql, $con);
while($row = mysql_fetch_assoc($rs_result)):
$aid=$row['albumid'];
$aimage=$row['image'];
$aname=$row['name'];
$astatus=$row['status'];
?>
<div class="col-lg-4 col-md-6 col-sm-6 agile_gallery_grid">
<div class="hover ehover14">
<a href='#details?d=$aid' onclick='showfunction()'>
<img src="admin/acatch/<?=$aimage?>" class="img-responsive" alt="<?=$aname?>" width="200" height="200" data-picture_id="<?=$aid?>">
</a>
</div>
</div>
<div class="gallery_album" id="gallery_album_<?=$row['albumid']?>">
<?php
/**
* now collect all images associated with each album by using $aid
*/
$sql_images = "SELECT * FROM tbl_album_images WHERE fk_album_id = $aid";
$images_result = mysql_query($sql_images, $con);
while($image = mysql_fetch_assoc($images_result)):
?>
<div class="gallery_album_image"><img src="<?=$image['dir_and_filename']?>"></div>
<?php
endwhile;
?>
</div>
<?php endwhile; ?>
What we are doing here is gettign all the albums as you allready does. But we introduce a subquery inside the first while-loop to fetch all associated images for each album.
We put these images inside new div-container with a unique album id you can use to show or hide the actual album with your showfunction()
Use CSS and javascript to show or hide accordingly.
OBS! WARNING!! Your mysql queries, and the one I provided, is very very BAD!
Have a look into prepared statement using php PDO or mysqli...

Looping through PHP database with columns that link to specific profiles

I have a website where I am getting information of college student profiles on a database and displaying it as a linked collection. When I'm looping through the database I want to give each row a specific link to the profile of the student. Right now I am linking it to "profilePage.html" with generic information but I want it to be correlated with the row the user chose on the last(college) page.How do I save/transfer that information to the page. I do not want multiple profile pages but one template that is filled with the user previous choice.
<?php
$result = mysql_query("SELECT * FROM student_info WHERE college='Boston College'", $db);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
?>
<a href="profilePage.html" class="collection-item">
<div class="row summary">
<div class="col s4 center">
<img class = "profile-pic" src="img/defaultProfile.jpg">
</div>
<div class="col s8">
<div class="title"> <?php echo $row[student_Name]; ?> </div>
<div class="black-text condensed thin"><i class="tiny material-icons">today</i> Founder, CEO at Linkle since January 1st, 2015</div>
<div></div>
</div>
</div>
</a>
<?php } ?>
Key thing, my urls are mysite.com/college.php and have no id's to specify them.
Structure of the Database student_info:
Shows the structure of the database
First, do you have an URL Rewriting ? If not, your target page should be a PHP page, like profilePage.php.
Your link to this page have to include a parameter (Query String) which is, for example, the student's ID :
<a href="profilePage.php?id=<?php echo $row['id'] ?>" class="collection-item">
This type of URL will be generated: profilePage.php?id=36
In profilePHP.php, retrieve the parameter in the Query String :
<?php
$idStudent = mysql_real_escape_string($_GET['id']);
?>
mysql_real_escape_string() is really important, it prevents SQL injections.
After that, you could retrieve the student's informations with a SQL query.
<?php
$idStudent = mysql_real_escape_string($_GET['id']);
$sql = sprintf("SELECT * FROM student_info WHERE id = %s", $idStudent);
$query = mysql_query($sql);
$student = mysql_fetch_object($query);
// you should check if the ID exists, and if there is 1 result
?>
<p>Student name is <?php echo $student['student_Name'] ?></p>
A little advice: mysql_query() will disappear soon, you should take a look at PDO.

How can I update with a form using MYSQLI

I'm lost on MySQLi. Manages a blog on standard mysql query, MySqli threw me. Followed a tutorial for inserting into a database. Notice the link for Edit. Not sure how to jump to a edit page to update. It this the wrong way of doing it? I think it's the echo that is the echo that is the issue?
<?php
$sql = "
SELECT snippets.Title, snippets.Link, snippets.Text, snippets.Created, camp_names.ribbon as Ribbon, camp_names.alt_text, camp_names.name as Campaign, camp_names.id
FROM snippets
LEFT JOIN camp_names ON snippets.Campaign = camp_names.id
ORDER BY camp_names.id ASC
";
$results = $db->query($sql);
if($results->num_rows) {
While($row = $results->fetch_object()) {
echo "
<div class='snippets'>
<div class='title'><h5><a href=''>{$row->Campaign}</a></h5><strong>{$row->Title}</strong> - Created:{$row->Created}</div>
<div class='ribbon_wrapper'>
<div class='ribbon'><img src='{$row->Ribbon}' alt='{$row->alt_text}' /></div>
<div class='ribbon_text'>{$row->Text}...<a href='{$row->Link}'> Read more</a></div>
<a href='#'>edit</a>
</div>
</div>
";
}
} else {
echo 'No Results';
}
?>

Get data using variable from query string?

I hope the title I used here was understandable...
I have a database with two columns: ward_id and ward_name.
I wish to create dynamic pages for each ward and have the ward_name show in the page title. I have created a header.php file which I am including.
I am passing the id through the URL using ....?wid={$row['ward_id']} which is working fine when I create other queries that use that id to get data from the database.
However the problem I am having is that the page refuses to display the ward_name as the page title. I expected something like this to work:
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$pagetitle = "$row['ward_name']";
}
But it doesn't, I have tried so many variations on the above I can't possibly remember them all now so I really hope someone can help me... Here is the code as it currently stands:
Header Page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title><?php echo $pagetitle; ?></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wholepage">
<div class="headlinewrapper">
<div class="headline">
<h1></h1>
<h2></h2>
</div>
</div>
<div class="headlinesidewrapper">
<div class="headlineside">
<p>shv jsfj sjnsf jnsf nsnf nj njsfn
njfjn sfns njf njnsf njs dgbjn dn jnd njjn dd d d nj njd njnd njd nn djndj njd</p>
</div>
</div>
<div class="topnavigation">
<ul>
<li>Home</li>
<li>Boroughs</li>
<li>Wards</li>
</ul>
</div>
<div class="sidebar">
</div>
<div class="mainpagewrapper">
Dynamic page:
<?php
$pagetitle = "Hello";
include ('header.php');
?>
<div class="mainpage">
<div class="infobox">
</div>
<?php
require('mysqli_connect.php');
mysql_select_db('onetwom2_london');
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
echo "<div class=\"boroughlist\"><p>{$row['ward_name']}</p></div>" ;
}
$pagetitle = $result;
?>
<div class="clear">
</div>
</div>
</div>
</div>
</body>
</html>
So I just want to know how/if it is possible to match the id passed through the URL to the ward_id stored on the database and then have the page title display the ward_name linked to that id. I apologise if this is a really easy question, I have spent hours trying to work this out and I am completely stumped! (the code I posted above is just the end result of 5 hours of frustration so please appreciate I have tried hard before asking you for help :) )
You should step through the problem to see where it goes awry, var-dump $pagetitle in the while loop. See what is being stored if it comes out as NULL you are not retrieving anything from the DB and there is an issue with either Query. if it has the correct variable the problem is with your PHP. Var_dump $pagetitle in your header.php file to be sure it is getting the correct variable.
Let me know the outcome and I can help you from there
<?php
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$pagetitle = "$row['ward_name']";
//Step Through The Problem
var_dump($pagetitle);
}
include ('header.php');
?>
<div class="mainpage">
<div class="infobox">
</div>
<?php
require('mysqli_connect.php');
mysql_select_db('onetwom2_london');
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
echo "<div class=\"boroughlist\"><p>{$row['ward_name']}</p></div>" ;
}
$pagetitle = $result;
?>
<div class="clear">
</div>
</div>
UPDATED - Try This
<?php
require('mysqli_connect.php');
mysql_select_db('onetwom2_london');
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$pagetitle = $row['ward_name'];
//Step Through The Problem
var_dump($pagetitle);
}
include ('header.php');
?>
<div class="mainpage">
<div class="infobox">
</div>
<?php
$result2 = mysql_query($query);
while ($row2=mysql_fetch_array($result2))
{
echo "<div class=\"boroughlist\"><p>{$row2['ward_name']}</p></div>" ;
}
?>
<div class="clear">
</div>
</div>
Do yourself a favor and use some ORM or library that gives you parameterized queries.
This code opens you right up for SQL-injection attacks:
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
First of all, avoid using double quotes as much as possible. Use single ' quotes instead. Double quotes makes php look for variables in the string which will be parsed. Using single quotes, any variables in the string will be echo'd as plain text, increasing overall performance.
So,
instead of
$pagetitle = "$row['ward_name']";
you want to use
$pagetitle = $row['ward_name'];
The same here:
echo "<div class=\"boroughlist\"><p>{$row['ward_name']}</p></div>";
should be changed into:
echo '<div class="boroughlist"><p>'.$row['ward_name'].'</p></div>';
Using single quotes makes \" also obsolete, making the code more readable and it'll be easier to write.
 
For working with databases in PHP I recommend you to work with a MySQLi Class. Have a look at https://github.com/ajillion/PHP-MySQLi-Database-Class . It's easy to implement and the learning curve is low.
MySQLi is the successor of MySQL (which is deprecated by now). With MySQLi prepared statements got introduced which make your queries containing (user) input save against SQL Injection. PDO would be even better, but it's harder to use.
Regarding $wardid = $_GET['wid'];: Make sure the value is being interpreted as integer. So try this:
$wardid = (int) $_GET['wid']; // type cast to integer aka Type Juggling
$query = 'SELECT ward_name, ward_id FROM wards WHERE ward_id=`'.$wardid.'` LIMIT 1';
Notice the LIMIT 1. This limits the query to one result, making it perform better as it stops right after it has found a result.
Good luck on your way learning more about SQL and PHP :-)
Edit:
According to a comment from the questioner, I want to add a rewritten example of the code given in the question:
<?php
// I'll demonstrate how to use the MySQLi Class
require_once('mysqlidb.php');
// Connect to the database
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
// Get the wid from the uri
$wardid = $_GET['wid'];
// Fetch the page title from the db
$result = $db->where('ward_id', $wardid)->get('wards', 1);
$pagetitle = $result['ward_name'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $pageTitle; ?></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- A templating engine like smarty would make things easier -->
<section class="whole-page">
<div class="headline-wrapper">
<div class="headline">
<h1></h1>
<h2></h2>
</div>
</div>
</section>
<div class="headline-sidewrapper">
<div class="headline-side">
<p>Lorem ipsum...</p>
</div>
</div>
<nav class="top-navigation">
<ul>
<li>Home</li>
<li>Boroughs</li>
<li>Wards</li>
</ul>
</nav>
<aside class="sidebar"></aside>
<section class="mainpage-wrapper">
<!-- Dynamic page part - I recommend using a separate template that will be included here -->
</section>
</body>
</html>
This is a basic example using the MySQLi Database Class. I recommend you to use a template engine like smarty to make jobs like this easier. Also consider reading 'Separation of concerns'.

Displaying information from a database in a loop

On my website i currently have an events page. Each event is read and displayed using a database. for each row in the database i have created a new div like:
<body>
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
$result = mysql_query('SELECT * FROM test ORDER BY timestamp DESC LIMIT 3;') ?>
<?php while($row = mysql_fetch_assoc($result)) : ?>
<div class="aboutUsContenttest">
<div class="boxheader"><?php echo $row['a'] ?><br></div>
<div class="aboutUsContentText"> <?php echo $row['b'] ?></div>
</div>
<?php endwhile ?>
</body>
this displays 3 different events.....
what i want to do is have an option to "Read More" meaning that i could click on a link which takes me to a separate page with more information about each event. how would i achieve this for say the second event? how would it know to take the information from the second row or div which has been created?
i hope this makes some sort of sense
Thank you
Pass the parametr in the address:
$limit = isset($_GET['view_all']) ? "" : "LIMIT 3";
$result = mysql_query("SELECT * FROM test ORDER BY timestamp DESC {$limit};");
Just have a page named the value of $row['b'] with a php file extension, and create an anchor with the href set to '$row['b'].php'
or, you could add the name of the page as a field in your database.
<body>
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
$result = mysql_query('SELECT * FROM test ORDER BY timestamp DESC LIMIT 3;') ?>
<?php while($row = mysql_fetch_assoc($result)) : ?>
<div class="aboutUsContenttest">
<div class="boxheader"><?php echo $row['a'] ?><br></div>
<div class="aboutUsContentText"> <?php echo $row['b'] ?></div>
<div><?php echo 'Read More'?></div>
</div>
<?php endwhile ?>
</body>

Categories