i am completely new to this world and i am trying to get more confident with PHP and MYSQL, so i am playing with a small web application just to fetch and retrieve data with MYSql and PHP.
I created a table in HTML and my goal is to retrieve this data from a mysql table with PHP
The problem is that the data are displayed twice... Can you help me understand where is error ?
Below the code :
<?php
session_start();
include_once("database.php");
$db = $conn;
$query = " SELECT categoria FROM categoria_prodotto";
$result = $db->query($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>test</title>
</head>
<body>
<section id="main-page">
<div class="link">
<span> Create a new purchase table </span>
</div>
<table>
<tr>
<td> category </td>
<td> product </td>
</tr>
<?php while ($row = mysqli_fetch_array($result)) :
foreach ($row as $temp) {
$query1 = "SELECT `nome` FROM `supermarket`.`lista_prodotto` WHERE `categoria_prodotto` = '$temp' ORDER BY `categoria_prodotto` DESC";
$result1 = $db->query($query1);
?>
<tr>
<td><?php echo $row[0]; ?> </td>
<td>
<?php while ($row1 = mysqli_fetch_array($result1)) :
echo $row1[0]; ?>
<?php endwhile;
}
endwhile; ?>
</td>
</tr>
</table>
<div class="link">
<span> Store a new product </span>
</div>
</section>
</body>
</html>
////
And here the result in browser with two row with same data duplicated each time
[here][1]
Thank you in advance for helping me to troubleshoot my problem :)
[1]: https://i.stack.imgur.com/XEBsi.jpg
You have some unnecessary loops, also if you use the object oriented version of the MySQLI API its a lot easier to read. I also change the query to use a Prepared parameterised query that you bind data to before the executing the query, much safer and protects you against SQL Injection
<?php
session_start();
include_once("database.php");
$db= $conn;
$query = "SELECT categoria FROM categoria_prodotto";
$result = $db->query($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>test</title>
</head>
<body>
<section id="main-page">
<div class="link">
<span> Create a new purchase table </span>
</div>
<table>
<tr>
<td> category </td>
<td> product </td>
</tr>
<?php
while($categoria_prodotto = $result->fetch_assoc()):
$query1 = "SELECT `nome`
FROM `supermarket`.`lista_prodotto`
WHERE `categoria_prodotto` = ?
ORDER BY `categoria_prodotto` DESC";
$stmt1 = $db->prepare($query1);
$stmt1->bind_param('s', $categoria_prodotto['categoria']);
$stmt->execute();
$result1= $stmt->get_result();
$supermarket = $result1->fetch_assoc();
?>
<tr>
<td><?php echo $categoria_prodotto['categoria']; ?></td>
<td><?php echo $supermarket['nome']; ?></td>
?>
<?php
endwhile;
?>
</td>
</tr>
</table>
</section>
</body>
</html>
Related
So I got these issues when I tried to extract data from the database. My DB connection is working fine. It is showing "Database connection established" and inside my index.php I wrote a for each loop to get the data and inside my HTML code, I display it inside the table. I got these errors:
Notice: Undefined variable: jokes in C:\xampp\htdocs\comp1321_database\jokes\jokes.html.php on line 16
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\comp1321_database\jokes\jokes.html.php on line 16
Here is the HTML and php code to display the data:
<?php include_once 'admin/includes/helpers.inc.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Jokes</title>
</head>
<body>
<p>Add your own joke</p>
<p>Here are all the jokes in the database</p>
<!-- into a table -->
<table border="1">
<?php foreach ($jokes as $joke): ?>
<!-- <form action="?deletejoke" method="post"> -->
<tr>
<td><?php html($joke['joketext']);?></td>
<td><?php $display_date = date("D d M Y", strtotime($joke['jokedate']));
html($display_date); ?>
</td>
<td><img height="100px" src="images/<?php html($joke['image']);?>"
/></td>
<td><input type="hidden" name="id" value="<?php echo $joke['id'];
?>">
<input type="submit" value="Delete"></td>
</tr>
<!-- </form> -->
<?php endforeach; ?>
</table>
<?php include 'admin/includes/footer.inc.html.php';?>
</body>
</html>
and here is the index.php:
<?php
// selection block
include 'admin/includes/db.inc.php';
//
try
{
$sql = 'SELECT * FROM joke';
$result = $pdo->query($sql);
} catch (PDOException $e) {
$error = 'Error fetching jokes' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row) {
$jokes[] = array(
'joketext'=> $row ['joketext'],
'jokedate'=> $row['joketext'],
'image'=> $row['image']
);
}
include 'jokes.html.php';
?>
Many thanks.
Initialize your jokes variable before you try to use it, ie:
$jokes = [];
try
{
$sql = 'SELECT * FROM joke';
$result = $pdo->query($sql);
} catch (PDOException $e) {
$error = 'Error fetching jokes' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row) {
$jokes[] = array(
'joketext'=> $row ['joketext'],
'jokedate'=> $row['joketext'],
'image'=> $row['image']
);
}
You need define $jokes on your php file, you can do it on header of file.
<?php include_once 'admin/includes/helpers.inc.php';?>
<?php
$jokes = someGetJokesFunction(); // write function to get data from database
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Jokes</title>
</head>
<body>
<p>Add your own joke</p>
<p>Here are all the jokes in the database</p>
<!-- into a table -->
<table border="1">
<?php foreach ($jokes as $joke): ?>
<!-- <form action="?deletejoke" method="post"> -->
<tr>
<td><?php html($joke['joketext']);?></td>
<td><?php $display_date = date("D d M Y", strtotime($joke['jokedate']));
html($display_date); ?>
</td>
<td><img height="100px" src="images/<?php html($joke['image']);?>"
/></td>
<td><input type="hidden" name="id" value="<?php echo $joke['id'];
?>">
<input type="submit" value="Delete"></td>
</tr>
<!-- </form> -->
<?php endforeach; ?>
</table>
<?php include 'admin/includes/footer.inc.html.php';?>
</body>
</html>
I haven't done this type of work in a long time, i'm sort of rusty still and really tired.
So here goes nothing, I have 2 search.php one for client side and one for server side. Im also using link.php to handle the mysql request. If there could be a kind soul to look over this mess would be great.
Notice: Undefined variable: id in C:\dummy\htdocs\connection\search.php on line 5
Notice: Undefined variable: upc in C:\dummy\htdocs\connection\search.php on line 7
Notice: Undefined variable: row in C:\dummy\htdocs\connection\search.php on line 28
Mysql connection(connection/link.php)
<?php
include 'config.php';
$link = mysqli_connect($host, $user, $password, $db);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
client side search.php(public_Html/search.php)
<!DOCTYPE html>
<html lang="en">
<?php include 'connection/link.php'; ?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<title>Inventory</title>
<style>
.redrum {
transform: translate(-50%, -50%);top:50%;left: 61%;position: absolute;right: 0;bottom: 0;
}
</style>
</head>
<body>
<h1><img src="" width="80px">8Ballshop Products</h1>
<div class="container">
<form style="height:40px" action="" method="GET">
<input class="form-control mr-sm-2" type="text" placeholder="ID or Link" name="search">
</form>
<?php include 'connection/search.php'; ?>
</div>
</body>
</html>
Server Side search.php(connection/search.php)
<?php
$sql = "SELECT products.id, products.upc FROM inventory.products";
if( isset($_GET['search']) ){
$name = mysqli_real_escape_string($link, htmlspecialchars($_GET['search']));
$sql = "SELECT products.id as id, products.upc FROM inventory.products WHERE products.id = '$id';
UNION
SELECT products.id as id, products.upc WHERE products.upc = '$upc'";
}
if ($result = mysqli_query($link, $sql)) {
?>
<table class="table table-striped">
<tr>
<th>Product ID</th>
<th>Product Link</th>
</tr>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['upc']; ?></td>
</tr>
<?php
}
}
?>
</table>
<?php echo $row['products.upc']; ?>
<?php mysqli_close($link); ?>
</div>
Based on your errors, you haven't declared $id or $upc anywhere.
You declare $name, but you don't use is, so maybe that was supposed to be $id?
You use products.upc later on, so is that supposed to be $upc?
A while loop is supposed to have a comparison in the parenthesis, not an assignment. Are you wanting a foreach instead? If you do, you should assign your mysqli_fetch_assoc to an array variable first.
while ($row = mysqli_fetch_assoc($result)) {
Becomes:
$resultsArray = mysqli_fetch_assoc($result);
foreach ($resultsArray as $row) {
https://www.php.net/manual/en/control-structures.foreach.php
Also, just because admins are the only uses of these pages, it doesn't mean they won't accidentally do something stupid, or someone who shouldn't have access will. It's always a good bit of practice to do basic security, such as SQL injection prevention, at all times.
This is a fairly straight forward DB request, the array 'data' display's correctly when using the pre_r() function but I'm running into an issue with the HTML table side of this, I can't get it to display any records. I'm missing something obvious here that is eluding me, any help?
<?php
$mysqli= new mysqli('localhost', 'username', 'password', 'DB') or die(mysqli_error($mysqli));
$data = $mysqli -> query("SELECT * FROM line_job WHERE JOB_NO=36934 AND LINE_NO=2") or die($mysqli->error);
pre_r($data ->fetch_assoc()); //recordset array
function pre_r( $array ) {
echo '<pre>';
print_r($array);
echo '</pre>';
}
?>
<!doctype html>
<html lang="en">
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" src="/css/bootstrap.min.css" >
<link href="/css/bootstrap.css" rel="stylesheet" type="text/css">
<title>[![enter image description here][1]][1]Detail</title>
</head>
<body>
<div class="row justify-content-center">
<div class="container">
<table class="table">
<thead>
<tr>
<th>Status</th>
<th>Job Type</th>
<th>Resp. Party</th>
</tr>
</thead>
<?php
while ($data = $data->fetch_assoc()): ?>
<tr>
<td><?php echo $data['STATUS'];?></td>
<td><?php echo $data['JOB_TYPE'];?></td>
<td><?php echo $data['RESP_PRTY'];?></td>
</tr>
<?php endwhile;?>
</table>
</div>
</div>
</body>
</html>
$mysqli ->query() returns a mysqli_result object. This object has a pointer pointing to the first record. Everytime you call fetch_assoc() on it, it returns a single record and increments the pointer by one to point to the next row OR returns NULL if there are not more rows.
Obviously, your Mysql query returns one row. By the time you call $data->fetch_assoc() the second time, there are no more rows left to fetch in the $data.
I am trying to make page in php/html that will display a "product's details." I have it displaying the icon and the link to the "details page," but it will not display ONLY one item on the "details page." Currently, the product's page (where the icon and the link are) will link to the "details page" just fine. However, when the page loads it loads every item in the sql database that has an 'ID.' I expected it to only take the item's id and display the page related to that item, however I received a cluster of them all... The code I have is what follows. I am currently trying to learn PHP so please if I make an error, a really bad one like something that isn't efficient. Please post the more efficient way of doing it. I am learning it the way I was taught at school.
<?php
//This page display a topic
include('admin/variable.php');
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
$dn1 = mysql_fetch_array(mysql_query('select c.id, c.name, c.description, c.price, c.quantity, c.itemID, c.imgName, c.position, (select count(t.id) from topics as t where t.parent=c.id and t.id2=1) as topics, (select count(t2.id) from topics as t2 where t2.parent=c.id and t2.id2!=1) as replies from categories as c group by c.id order by c.position asc'));
if($dn1['id']>0)
{
?>
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo $design; ?>/style.css" rel="stylesheet" title="Style" />
<title><?php echo htmlentities($dn1['name'], ENT_QUOTES, 'UTF-8'); ?> - <?php echo htmlentities($dn1['itemID'], ENT_QUOTES, 'UTF-8'); ?> - KB Computers</title>
</head>
<body>
<div class="header">
<img src="<?php echo $design; ?>/images/logo.png" alt="Forum" />
</div>
<div class="Content">
<?php
?>
<h1><?php echo $dn1['name']; ?></h1>
<?php
$dn2 = mysql_query('select c.id, c.name, c.description, c.price, c.quantity, c.itemID, c.imgName, c.position, c.position, (select count(t.id) from topics as t where c.parent=c.id and t.id2=1) as topics, (select count(t2.id) from topics as t2 where t2.parent=c.id and t2.id2!=1) as replies from categories as c group by c.id WHERE c.id = ' . $id .' order by c.position asc');
//////////////////////////////////////////////////////////
while($dnn2 = mysql_fetch_array($dn2)) //This is line 30!
//////////////////////////////////////////////////////////
{
$parent = $dnn2['parent'];
if(isset($_GET['id']))
{
if($_GET['id'] == $parent){
?>
<div id="thing">
<table>
<tr>
<th><?php echo $dnn2['imgName']; ?></th>
</tr>
<br />
<tr>
<th><?php echo $dnn2['price']; ?></th>
</tr>
<br />
<tr>
<th> <?php echo $dnn2['description']; ?></th>
</tr>
<br />
<tr>
<th><?php echo $dnn2['itemID']; ?></th>
</tr>
<?php
if(isset($_SEESION['username']) and $_SESSION['username'] == $admin){?><div class="edit"><img src="<?php echo $design; ?>/images/edic.png" alt="Edit" /></div>
<?php } ?>
</table></div>
<?php
}else{echo 'The parent and id values are not the same.';}
}}
?>
</div>
</body>
</html>
<?php
}
else
{
echo '<h2>This topic doesn\'t exisc.</h2>';
}
}
else
{
echo '<h2>The ID of this topic is not defined.</h2>';
}
?>
<?php
//This page display a topic
include('admin/variable.php');
include('home.php');
if(isset($_GET['id']))
{
$dn1 = mysql_query('select
c.id,
c.name,
c.description,
c.price,
c.quantity,
c.itemID,
c.imgName,
c.parent,
c.position,
(select count(c.id) from categories as c where c.parent=c.id) as categories, (select count(c.id) from categories as c where c.parent=c.id and c.id!=0) as replies from categories as c group by c.id order by c.position asc');
if($dn1 === false){
die(mysql_error());
}
while($dnn1 = mysql_fetch_array($dn1))
{
$parent = $dnn1['parent'];
if($_GET['id'] == $parent){
?>
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="require/style.css" rel="stylesheet" title="Style" />
<title><?php echo htmlentities($dnn1['name'], ENT_QUOTES, 'UTF-8'); ?> - <?php echo htmlentities($dnn1['itemID'], ENT_QUOTES, 'UTF-8'); ?> - KB Computers</title>
</head>
<body>
<div class="Content">
<div style="background:white; height:800px;">
<div id="shopNav">
<ul>
<li class="end">Shop</li>
<li>Catagories</li>
<li>New Products</li>
<li>My Account</li>
<li class="end2">Checkout</li>
</ul>
</div>
<div id="thing">
<table><h1><?php echo $dnn1['name']; ?></h1>
<tr>
<th><?php echo '<img src="image/' . $dnn1['imgName'].'" alt="' . $dnn1['imgName']. '" width="128" height="128"'; ?></th>
</tr>
<tr>
<th><?php echo $dnn1['price']; ?></th>
</tr>
<tr>
<th class="tableDesc"> <?php echo $dnn1['description']; ?></th>
</tr>
<tr>
<th><?php echo $dnn1['itemID']; ?></th>
</tr>
<?php
if(isset($_SEESION['username']) and $_SESSION['username'] == $admin){?>
<tr>
<img src="<?php echo $design; ?>/images/edic.png" alt="Edit" />>
</tr>
<?php } ?>
<tr>
<th> </th>
</tr>
</table>
</div>
<?php include("require/rightBar.html"); ?></div><?php include("require/footer.html");
}
}
}else{echo 'That product doesnt exist!';}
?>
</div>
</body>
I need help with updating the selected item from a list populated via php and updated with jquery, here is what I have:
my update.php front-end
<?php include_once('db.php'); ?>
<!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 http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Update Collected</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="print, projection, screen" />
<link rel="stylesheet" href="css/bootstrap.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/bootstrap-responsive.css" type="text/css" media="screen" />
</head>
<body>
<?php
$sql="SELECT * FROM qrnumber";
$result=mysql_query($sql);
?>
<div class="container-fluid main">
<div class="row-fluid ">
<div class="span12">
<span class="success"></span>
<table cellpadding="0" cellspacing="0" id="tablesorter-demo" class="tablesorter table table-striped">
<thead>
<tr>
<th>id</th><th>Name</th><th>Points</th><th>Collected</th><th>Action</th>
</tr>
</thead>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr id="<?php echo $row['id']; ?>">
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['points']; ?></td>
<td><?php echo $row['total']; ?></td>
<!-- and so on -->
<td>
<input id="total" class="required" type="text" name="total">
<button class="update_btn" rel="<?php echo $row['id']; ?>">update</button>
</td>
</tr>
<?php endwhile; ?>
<?php
// close connection
mysql_close();
?>
</table>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.js"></script>
<script>
$(document).ready(function(){
$(function() {
$("#tablesorter-demo").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']});
$("#options").tablesorter({sortList: [[0,0]], headers: {
3:{sorter: false}, 4:{sorter: false}}});
);
$('.update_btn').click(function(){
$('.success').text("loading...");
var id = $(this).attr('rel');
var total = $('#total').val();
$.post('call.php', {Id:id, Total:total}, function(data) {
alert(data);
});
});
});
</script>
</body>
</html>
This is my process.php file
<?php
include_once('db.php');
var_dump($_POST);
if (isset($_POST['collected'])){
$collected = mysql_real_escape_string(htmlentities($_POST['collected']));
}
$id = $_POST['id'][0];
$total = $_POST['total'];
echo $id. $total;
mysql_query("UPDATE qrnumber SET total='$total'
WHERE id='$id'");
?>
The issue is that when I post a number to the input field, it makes connection to my processing php file, but does not update the content, it connects to db and passes the values from update.php to process file(call.php). Then, it sets all of the records to '0', can someone help, please.
Thanks,
jv
Your $_POST is wrong in PHP. PHP only creates an array of values in $_POST/$_GET if the fieldname submitted by the client ends with [] characters. e.g.
will produce the following $_POST array:
$_POST = array(
'not_an_array' => 'bar'
'is_an_array' => array (
0 => 'baz'
1 => 'qux'
)
);
Since the Id andTotalyou're submitting in the ajax call don't have[]` in the names, they'll just be plain single values in PHP, e.g.
$id = $_POST['Id'];
$total = $_POST['Total'];
And nod that you're STILL vulnerable to SQL injection attacks, since you're trying to use $id directly in your query without escaping that either. ANY external data going into a query string is an attack vector. You cannot escape only SOME of the values and assume you're safe.