I am working on a website whereby a load of advertisers are stored in the DB and then displayed to the user by there logo. I know storing directly in to the DB for images is not the done thing, however, I am starting out this way, to get the website running and then will refactor to move to a much more suitable approach.
Currently, I have the following PHP code:
<?php
session_start();
require_once "config.php";
// Create connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM advertisers";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>advertiser_Name</th>";
echo "<th>advertiser_URL</th>";
echo "<th>advertiser_Category</th>";
echo "<th>advertiser_logo</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['advertiser_id'] . "</td>";
echo "<td>" . $row['advertiser_Name'] . "</td>";
echo "<td>" . $row['advertiser_URL'] . "</td>";
echo "<td>" . $row['advertiser_Category'] . "</td>";
echo "<td>" . $row['<img src="data:image/jpeg;base64,'.base64_encode($row['advertiser_logo']).'"/>'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
However, the images are displayed when called from the DB but they are displayed in the warning message rather than in the table?
<?php
session_start();
require_once "config.php";
// Create connection
if ($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM advertisers";
if ($result = mysqli_query($link, $sql))
{
if (mysqli_num_rows($result) > 0)
{
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>advertiser_Name</th>";
echo "<th>advertiser_URL</th>";
echo "<th>advertiser_Category</th>";
echo "<th>advertiser_logo</th>";
echo "</tr>";
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['advertiser_id'] . "</td>";
echo "<td>" . $row['advertiser_Name'] . "</td>";
echo "<td>" . $row['advertiser_URL'] . "</td>";
echo "<td>" . $row['advertiser_Category'] . "</td>";
echo "<td><img src='data:image/jpeg;base64," . base64_encode($row['advertiser_logo']) . "'/></td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
}
else
{
echo "No records matching your query were found.";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
The fact that is showing the image in the warning is because you're using a tag with the source as an array key which is not correct.
The array keys, so what is inside the square bracket, is the reference to the array position. If you're familiar with C for example is the 0, 1, ecc.. and not the value itself.
Yes as #NigelRen mentioned this row $row['<img src="data:image/jpeg; looks very bad.
I think you should use:
echo "<td><img src='data:image/jpeg;base64," . base64_encode($row['advertiser_logo']) . "'/></td>";
Related
I would like to retrieve my results from my DB in this format using Bootstrap.
Below is my PHP code that I'm currently using, the first entry I want the image to be bigger then the rest.
<?php
$article = mysqli_connect("localhost", "root", "", "blog");
// Check connection
if($article === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM news";
if($result = mysqli_query($article, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<container>";
echo "<row>";
echo "<th>id</th>";
echo "<th>title</th>";
echo "<th>body</th>";
echo "<th>image</th>";
echo "</div>";
while($row = mysqli_fetch_array($result)){
echo "<row>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['body'] . "</td>";
echo "<td>" . $row['image'] . "</td>";
echo "</row>";
}
echo "</div>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($article);
}
// Close connection
mysqli_close($article);
?>
I think you should have the condition to check for the first data in your loop to apply a bigger image size.
You can simply add condition:
$resultNum = 1;
while($row = mysqli_fetch_array($result)){
if($resultNum == 1) {
// TODO: show bigger image
} else {
// usual image
echo "<row>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['body'] . "</td>";
echo "<td>" . $row['image'] . "</td>";
echo "</row>";
}
$resultNum++;
}
Just make a counter and then do a condition using the first number of the counter
Your code simplyfied:
$query = mysqli_query($article, "SELECT * FROM news");
$n = 1; //start the counter
if(mysqli_num_rows($query) > 0){ //detect if have rows
foreach ($query as $key => $value) {
if($n == 1){
//print the big image
echo $value["id"];
}else{
//print the little image
echo $value["id"];
}
$n++;
}
}else{
echo "No data founded";
}
<html>
<head>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8" />
<title>Using file functions PHP</title>
</head>
<body>
<h1>Web Development - Lab05</h1>
<?php
require_once("settings.php");
$dbconnect = #mysqli_connect($host, $user, $pswd, $dbnm);
if($dbconnect->connect_errno >0)
{
die('Unable to connecto to database [' . $db->connect_error . ']');
}
$queryResult = "SELECT car_id, make, model, price FROM cars";
echo "<table width='100%' border='1'>";
echo "<tr><th>ID</th><th>Make</th><th>Model</th><th>Price</th></tr>";
//initiate array
$displayrow= mysqli_fetch_array($queryResult);
//initiate while loop to iterate through table
while($displayrow)
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Make'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($dbconnect);
?>
</body>
</html>
This is doing my head in, I cannot figure out why it will not display the actual data apart from the Table header. No matter what I used.
I have tried mysqli_fetch_array, mysqli_fetch_row, mysqli_fetch_assoc but nothing works.
Help and explanation why it was not displaying the data would be much appreciated :)
First: You aren't running a query, you are only putting the query text in a variable. You need to use mysqli_query.
Second: You should add mysqli_fetch_array to the loop.
For example:
while($displayrow = mysqli_fetch_array($queryResult))
{
}
Otherwise you are only getting the first row.
Third: Array keys are case sensitive. There is no $row['ID'], as Jeribo pointed out, it is $row['car_id'] as referenced in your query. $row['Make'] is not the same as $row['make'].
Please Precision to names of field in Query ( car_id,make,...)
while($displayrow= mysql_fetch_assoc($queryResult) )
{
echo "<tr>";
echo "<td>" . $displayrow['car_id'] . "</td>";
echo "<td>" . $displayrow['make'] . "</td>";
echo "<td>" . $displayrow['model'] . "</td>";
echo "<td>" . $displayrow['price'] . "</td>";
echo "</tr>";
}
If you want to query outside you still have to set it in the loop:
$result = $db->query($queryResult)
while($row = $result ->fetch_assoc()){
...
}
a Good Tutorial is shown here: http://codular.com/php-mysqli
$row needs to be initialized so why don't you try:
while($row = mysqli_fetch_array($queryResult))
{
....
}
You have to get the result set first and then try fetching array from result set
<?php
require_once("settings.php");
$dbconnect = #mysqli_connect($host, $user, $pswd, $dbnm);
if($dbconnect->connect_errno >0)
{
die('Unable to connecto to database [' . $db->connect_error . ']');
}
$query = "SELECT car_id, make, model, price FROM cars";
$resultSet=mysqli_query($dbconnect,$query)
echo "<table width='100%' border='1'>";
echo "<tr><th>ID</th><th>Make</th><th>Model</th><th>Price</th></tr>";
//initiate array
$displayrow= mysqli_fetch_array( $resultSet);
//initiate while loop to iterate through table
while($displayrow)
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Make'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($dbconnect);
?>
http://www.w3schools.com/php/func_mysqli_fetch_array.asp
i am passing images file names via textarea to php script to find information about each image in mysql db .The problem is i am trying to output those image file names that not found in mysql db and inform the user which image file names not found in mysql. my current code fails to output those missing records in db but it correctly outputs information about those images found in db. could any one tell me what i am doing wrong ?
foreach ($lines as $line) {
$line = rtrim($line);
$result = mysqli_query($con,"SELECT ID,name,imgUrl,imgPURL FROM testdb WHERE imgUrl like '%$line'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
//echo $result;
if($result == 0)
{
// image not found, do stuff..
echo "Not Found Image:".$line;
}
while($row = mysqli_fetch_array($result))
{
$totalRows++;
echo "<tr>";
echo "<td>" . $row['ID'] ."(".$totalRows. ")</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['imgPURL'] . "</td>";
echo "<td>" . $row['imgUrl'] . "</td>"; echo "</tr>";
}
};
echo "</table>";
echo "<br>totalRows:".$totalRows;
You can use mysqli_num_rows() in mysqli
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result))
{
$totalRows++;
echo "<tr>";
echo "<td>" . $row['ID'] ."(".$totalRows. ")</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['imgPURL'] . "</td>";
echo "<td>" . $row['imgUrl'] . "</td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='4'>Not Found Image:".$line.'</td></tr>';
}
You want to use mysqli_num_rows
if(mysqli_num_rows($result)) {
// Do your while loop here
}
Use mysqli_num_rows to compare the number of rows in the result set.
I have two tables in mysql
practice_sheets and parent_pin
And I want to use one select statement and get data from both tables.
I have tried
$result = mysqli_query($con,"SELECT * FROM practice_sheets AND parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
and also:
$result = mysqli_query($con,"SELECT * FROM practice_sheets, parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
I've never tried to do this before and the previous solutions are what I found searching.
Update
I think it would help if I included my full code. the table data is going into a table on my page. the student_name field from the practice_sheets and parents_student from parent_pin will be matched.
<?php
$con=mysqli_connect();
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM practice_sheets
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
$numrows = mysqli_num_rows($result);
if($numrows == 0) {
echo "<div class='alert alert-danger'>";
echo "No Entries, See your instructor for details.";
echo "</div>";
} else {
echo "<table class='mws-table table-striped table-hover'>";
echo "<thead align='center'>";
echo "<tr>";
echo "<th>Sheet Number</th>";
echo "<th>Total Minutes</th>";
echo "<th>Due Date</th>";
echo "<th>PIN</th>";
echo "<th>View</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody align='center'>";
while($row = mysqli_fetch_array($result)){
if ($row["total_min"]>=$row["required_min"]) {
echo "<tr class='success'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
} else {
echo "<tr class='info'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
mysqli_close($con);
}
?>
$result = mysqli_query($con,"SELECT *
FROM practice_sheets, parent_pin
WHERE student_name = parents_student
AND student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
Use explicit names for WHERE statament, e.g.
$result = mysqli_query("SELECT student_name.practice_sheets FROM practice_sheets AND parent_pin WHERE student_name.practice_sheets = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
MySQL will not AFAIK automatically check where the constraints are and rightly so considering that you may have conflicting names. Note that this is still pseudo code and you will need to change the fetched results accordingly. Usually it is considered to be good practice to also define explicitly the columns you wish to fetch, but otherwise you can use JOIN as well.
And to help writing shorter code, you can also use shorthands for the table names, e.g.
$result = mysqli_query("SELECT student_name.ps AS name, pin.pp AS pin FROM practice_sheets AS ps, parent_pin AS pp WHERE student_name.ps = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
Update
You also have in your updated version an issue. You call mysqli_fetch_array, which returns an ordered (i.e. numbered) array. If you wish to use keyed, use mysqli_fetch_assoc.
And you are closing the MySQL connection at the moment only if the query was successful. Move mysqli_close outside of the brackets.
I have an admin area in an ecommerce website whereby the admin can view all users on the allusers.php page. The users are listed in a table with their personal information, however i have a 'view profile' button near each user whereby if you was to click on it, it would take you to another page where you can view that specific users past orders.
the following is the code i have for allusers.php:
<?php
$result = mysql_query("SELECT * FROM customers ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>First Name</th><th>Surname</th><th>Address</th><th>E-Mail</th><th>Username</th><th>View Profile</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['surname']. "</td>";
echo "<td>" . $info['address1']. $info['address2']. $info['city']. $info['postcode']." </td>";
echo "<td>" . $info['email']. "</td>";
echo "<td>" . $info['username']. "</td>";
echo "<td>" . " <a href='view.php'>View</a> </td>";
}
}
echo "</tr>";
echo "</table>";
?>
the view.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM order WHERE ......dont know what to enter here")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders For This Customer Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>Product</th><th>Quantities</th><th>Date</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['quantity']. "</td>";
echo "<td>" . $info['date']. " </td>";
}
}
echo "</tr>";
echo "</table>";
?>
I have a mysql database with the following fields & tables:
Customers - id, name, surname, address1, address2, city, postcode, email, username, password
Products - serial, name, description, price, picture
Order - id, name, quanitity, price, date, username
Thanks for any help provided
Your code lacks any sort of security mechanisms... This is very bad, especially in an e-commerce setting.
Excusing that, you would pass the username to the view page in the URL.
echo "<td>" . " <a href='view.php?user=" . $info['username'] . "'>View</a> </td>";
In your view page, you would get the parameter from the URL and include it with your query.
if (isset($_GET) && isset($_GET['user'])) {
$user = mysql_real_escape_string($_GET['user']);
} else {
header('Location: allusers.php');
exit(); // boot them back to the previous page.
}
$result = mysql_query("SELECT * FROM order WHERE username = '" . $user . "'")
A simple method could be the follow. Replace this line in alluser.php
echo "<td>" . " <a href='view.php'>View</a></td>";
with this one
echo '<td>View</td>';
and then, in your view.php have
if (isset($_GET['username']) && $_GET['username'] != '')
{
$username = mysql_real_escape_string($_GET['username']);
$result = mysql_query("SELECT * FROM order WHERE username = '$username'");
}
else
{
// No user specified. Do other statements
}
Please note the use of:
The user of the mysql_real_escape_string() function to protect from Sql injection (would be better the use of a prepared statements)
The use of the parameter username in the first page to pass the value of the username to the second page
The use of the $_GET global array to retrieve the parameter
Try this:
allusers.php
<?php
$result = mysql_query("SELECT * FROM customers ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>First Name</th><th>Surname</th><th>Address</th><th>E-Mail</th><th>Username</th><th>View Profile</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['surname']. "</td>";
echo "<td>" . $info['address1']. $info['address2']. $info['city']. $info['postcode']." </td>";
echo "<td>" . $info['email']. "</td>";
echo "<td>" . $info['username']. "</td>";
echo "<td>" . " <a href='view.php?user={$info['username']}'>View</a> </td>";
}
}
echo "</tr>";
echo "</table>";
?>
view.php
<?php
$user = mysql_real_escape_string($_GET['user']);
$result = mysql_query("SELECT * FROM order WHERE user = '$user'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders For This Customer Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>Product</th><th>Quantities</th><th>Date</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['quantity']. "</td>";
echo "<td>" . $info['date']. " </td>";
}
}
echo "</tr>";
echo "</table>";
?>