i have a website i am constructing for a school project, in which i already have various webpages where i get tabular data from my database through the use of While and Foreach.
But on this page in question, i am attempting to retrieve data from various tables, in order for a user to choose a category, and a text and submit.
But for some reason it isn't outputting any data. If i attempt with only one table and without using the table.field method, and only typing the fields, it works.
But from what i know, to retrieve from various tables i have to do so.
Can annione help me out on this?
<html>
<head>
<script type="text/javascript" >
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$query = "SELECT texto.titulo,texto.ID,categoria.categoria,categoria.id FROM categoria,texto";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo "<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>'";
echo "<button type='submit'>Submeter</button>";
echo "<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>";
echo "<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if ($campo == "texto.titulo") {
echo "<tr><td>'".$valor."'</td>";
}
if ($campo == "texto.ID") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
if ($campo == "categoria.categoria") {
echo "<td>'".$valor."'</td>";
}
if ($campo=="categoria.id") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
}
}
echo "</form>";
echo "</table>";
echo "</center>";
?>
</body>
</html>
Added: Since both tables have a field called id, it won't let me simply put the field names, i have to also put the table name like i did. And yes, i have verified and both tables are populated with data, they work fine on other pages.
This is what I suggest (I didn't consider much code optimization).
<?php
$data = array();
mysql_connect('localhost', 'root', '') or die('problema na conexao');
mysql_select_db('trabalho1');
// Use the same field-names/aliases: id, info
$query = 'SELECT ID AS id, titulo AS info FROM texto';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
// Use the same field-names/aliases: id, info
$query = 'SELECT id, categoria AS info FROM categoria';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
?>
<html>
<head>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<center>
<table border='2'>
<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>
<tr><td colspan ='2'><button type='submit'>Submeter</button></td></tr>
<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>
<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>
<?php
foreach ($data as $row) {
echo '<td><input type="radio" name="nome" value="' . $row['id'] . '></td></tr>' .
'<tr><td>' . $row['id'] . '</td>';
}
?>
</form>
</table>
</center>
</body>
</html>
PS: Read about my response about double quotations. Should I use curly brackets or concatenate variables within strings?
Related
I have a problem regarding while loop. I have a option tag and hidden value inside the loop, the option tag work correctly for the dropdown list but the hidden value is not match with the selected dropdown list.
This is my code :
<?php
session_start();
require 'config.php';
$option1 = '';
$idseason='';
$season = '';
$query1 = "select id,description from codemaster_local where codeclass = 'season' and description like '%1st%' group by description";
$result1 = mysqli_query($doa,$query1);
while($row1 = mysqli_fetch_array($result1)) {
$option1 .= "<option value='".$row1['description']."'>".$row1['description']."</option>";
$hidden = "<input type=hidden name=id value='".$row1['id']."'>";
}
if(isset($_POST['submit'])) {
$season = $_POST['season'];
$idseason = $_POST['id'];
echo "Season :"; echo $season;echo "<br>";
echo "ID : ";echo $idseason;
}
?>
<html>
<head>
<link href="style/style.css" rel="stylesheet" type="text/css">
<link href="style/sty.css" rel="stylesheet" type="text/css">
<link href="style/dropdown.css" rel="stylesheet" type="text/css">
</head>
<body>
<form class="form-style-9" action="" method="post">
<table>
<tr><td><b>Season:</b></td>
<td> <select name="season" class="select-css">
<?php echo $option1; ?>
</select>
<?php echo $hidden; ?>
</td>
</tr>
</table><br>
<input type="submit" value="Search" name="submit">
</form>
</body>
</html>
For example, the id for 1st season 2005 should be 24800 but instead it choose the last id 30539. I select any of the season also still choose the last id. Is there any way to fix this?
$hidden is being overwritten upon every loop within your while. Resulting in one hidden field with the name: id, containing the value of the last row id retrieved. That is the value you receive upon submission.
while($row1 = mysqli_fetch_array($result1)) {
$option1 .= "<option value='".$row1['description']."'>".$row1['description']."</option>";
$hidden = "<input type=hidden name=id value='".$row1['id']."'>";
}
I suggest you change the option's value attribute to $row1['id']:
while($row1 = mysqli_fetch_array($result1)) {
$option1 .= "<option value='".$row1['id']."'>".$row1['description']."</option>";
}
This way, $_POST['season'] will then hold the corresponding id for the season selected.
Try putting the id in the option tag instead of a hidden tag:
while($row1 = mysqli_fetch_array($result1)) {
$option1 .= "<option value='".$row1['description']."' id='".$row1['id']."'>".$row1['description']."</option>";
}
I have written the below code as a test , but results are not comng in under the table I have created , the table appear along the top and all the results appear down the left hand side and even if I dont add anythig in the search all teh results show.?, cant see where I am going wrong. I am not worried about the actual HTML Look as it just a test. Appreciate the help. Error is
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel= "stylesheet" href="style5.css"/>
</head>
<boby>
<div class="third_bar">
<div class="second_image">
</div>
<div class="form"><form action= "search1.php" method="post">
<input type="text" name="search" id="search_bar" placeholder="" value="Search for your whisky here" max length="30" autocomplete="off" onMouseDown="active();" onBlur="inactive();"/><input type="submit" id="search_button" value="Go!"/>
</form>
</div>
</body>
</div>
</html>
search1.php
<?php
if (isset($_POST['search'])){
include ('connect.php');
$search = $_POST['search'];
$query = "SELECT * FROM whisky_results";
$result = mysqli_query($conn, $query) or die ('error getting data');
echo "<table>";
echo "<tr> <th>Whisky Name</th> <th>Whisky Desription</th> <th>Highest Price Recorded</th> <th>Lowest Price Recorded</th> </tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo "<tr><td>";
echo $row['description'];
echo "</td><td>";
echo "<tr><td>";
echo $row['highest_price'];
echo "</td><td>";
echo "<tr><td>";
echo $row['lowest_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
I've been doing a very simple php comment system, where the user simply types a comment and it appears on the site.However, I realised that the most recent comment would keep being posted if the user refreshed the page.
I figured it had something to do with the while loop in the getComments function, but I've tried header("Location: index.php") and it had another error, so I'm really out of ideas.
index.php:
<?php
date_default_timezone_set('Europe/Bucharest');
include 'dbh.inc.php';
include 'comments.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<?php
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('d-m-Y H:i:s')."'>
<textarea name='message'></textarea><br/>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
getComments($conn);
?>
</body>
</html>
Comments.inc.php:
<?php
function setComments($conn)
{
if (isset($_POST['commentSubmit']))
{
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
$result = mysqli_query($conn,$sql);
}
}
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
dbh.inc.php
<?php
$conn = mysqli_connect('localhost', 'root', '' , 'commentsection');
Any feedback is greatly appreciated.
So I do not know if this is a good thing, but it seems very practical.What I've finally done is:
I set up a session variable.Then instead of
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
I did
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
if($_SESSION["repeated"]!=$row['message'])
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
}
$_SESSION["repeated"]=$row['message'];
echo "</p></div>";
}
}
And it seems to be absolutely working!It has a minor glitch though :
If I delete all the variables in the database after I already posted a comment in this session, at some point it will post it again.(Not a big deal).
But that's all.
I was going for the post/redirect/get, but I was a bit confused and tried this out of curiosity and it worked.(To me)It seems a simpler approach, or is it something I'm not seeing?
easy fix!!!
add recuired to the forms
<input type='text' name='emne' placeholder='Subject' required
<input type='text' name='emne' placeholder='Subject' required>
update
Can anyone explain to me why I am getting duplicate messages instead of one?
how can I change my code so that when I type a comment and press "Comment" button, it will only display one message instead of duplicates! When I have one comment boxes it doesn't show duplicate comments, but if I have more than one then it starts duplicating!
COMMENT.INC.PHP
include 'cdbh.inc.php';
function setComments($con)
{
if (isset($_POST['commentSubmit'])) {
$uid = mysqli_real_escape_string($con,$_POST['uid']);
$date = mysqli_real_escape_string($con,$_POST['date']);
$message = mysqli_real_escape_string($con,$_POST['message']);
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
$result = mysqli_query($con,$sql);
}
}
function getComments($con)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($con,$sql);
while ($row=mysqli_fetch_assoc($result)) {
echo $row['uid'];
echo ":";
echo $row['message']."<br><br>";
}
}
page code
<?php
date_default_timezone_set('America/Los_Angeles');
include 'comment.inc.php';
include("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="comment.css" rel ="stylesheet">
</head>
<body>
<?php
$sql="Select * from tbl_images";
$result=mysqli_query($connection,$sql);
while ($row=mysqli_fetch_array($result)) {
?>
<img src="images/<?php echo $row['images_name'] ?>" width="200px" height="200px">
<?php
echo "<form method ='POST' action ='".setComments($con)."'>
<input type ='hidden' name ='uid' value='unknown'>
<input type ='hidden' name ='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea>
<button type ='submit' name='commentSubmit'>Comment</button>
</form>";
}
getComments($con);
?>
</body>
</html>
Maybe you are submiting all your forms instead of one..
check your database in order to know from what img comes each message.
If you have other code like javascript, you should post it.
Hi I have a page that displays all of the contents of my table. Alongisde each row of the table I also have a column containing a checkbox. When the user selects one or more rows by ticking the checkbox and pressing the submit button, I want just those rows to appear in a table on the next page (buy.php). I know it is basically a select statement per row that is selected. But I dont know how to approach this. Can anybody help? Thanks
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Shopping</title>
</head>
<body>
<form action='buy.php' method='post'>
<input type='submit' value='Submit' />
</form>
<h1>Buy</h1>
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items';
if ($r = mysql_query($query, $db)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
<td><input type='checkbox' name='buy[{$row['ID']}] value='buy' /></td>
</tr>";
}
print "</table>
</form>";
} else {
print '<p style="color: blue">Error!</p>';
}
mysql_close($db); // Close the connection.
?>
</body>
</html>
EDIT: I tried the suggestion below and I did not get a table. Just the title of the page appeard:
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Confirmation</title>
</head>
<body>
<h1>Order Details</h1>
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
foreach($_POST['buy'] as $item) {
$query = 'SELECT * FROM Items WHERE ID = $item';
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
} else {
print '<p style="color: blue">Error!</p>';
}
}
mysql_close($db);
?>
</body>
</html>
You need to create a dynamic SQL query.
1) I suggest you change your checkbox to the following
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
2) Loop through all of the buy options
<?php
foreach($_POST['buy'] as $item) {
// Append the ID (in the $item variable) to the SQL query, using WHERE `ID` = $item OR `ID` = $item and so on
}
?>
UPDATE:
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items WHERE ';
$item_count = count($_POST['buy']);
for($i = 0; $i < $item_count; $i++) {
$itemid = (int)mysql_real_escape_string($_POST['buy'][i]); // Secures It
$query .= '`ID` = '.$itemid;
if($i +1 < $item_count) {
$query .= ' OR ';
}
}
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
mysql_close($db);
?>
// this checkbox use
//buy.php foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item"; //use " "
// try it if any problem please carefully look you database table // download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK
// this checkbox use
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
//buy.php
foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item";
//use " "
// try it if any problem please carefully look you database table
// download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK