Data in my HTML forms vanishes when the web refreshes - php

I've tried to make an small chat only with PHP, HTML and MySQL. The main problem with it is that when you're writing and the web refreshes, the text you're writing disappears. How can I solve it? Here is the code:
Chat (MySQL connection details have been removed):
<?php
$_POST['text'] = '';
session_start();
include 'status.php';
$_SESSION['status'] = status($_SESSION['nick']);
if(IsSet($_SESSION['nick']) && IsSet($_SESSION['pass'])){
?>
<link rel="stylesheet" href="/style.css">
<link rel="icon" href="/icon.ico">
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "15";
header("Refresh: $sec; url=$page");
$_SESSION['text'] = $_POST['text'];
$con = mysqli_connect("","","","");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<body>
<h4>Chat: </h4>
<form align="center" name="form" method="POST" action="/chat/speak.php">
<?php echo $_SESSION['nick'] . ': '; ?>
<input name='text' type='text' value="<?php echo $_SESSION['text']; ?>" style="width: 500px;"><br>
Person: <select id="so" name="private">
<?php
$result = mysqli_query($con,"SELECT * FROM users ORDER BY nick");
while($row = mysqli_fetch_array($result))
{
$nick = $row['nick'];
echo "<option value='$nick' selected='selected'>$nick</option>";
}
?>
<option value="public" selected="selected"> PUBLIC </option>
</select>
<input type="submit" value="Speak!"></form>
</body>
<?php
echo '<hr/>';
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY time DESC");
echo "<div align='left' name='chat'>
<h2 align='center'><u>Conversation: </u></h2>";
echo '<hr/>';
echo "<ul style='list-style-type:none'>";
while($row = mysqli_fetch_array($result))
{
$author = $row['author'];
$message = $row['message'];
$color = $row['color'];
$p = $row['p'];
$destinatary = $row['PRIVATE'];
if($p == 1){
if($author == $_SESSION['nick'] || $destinatary == $_SESSION['nick']){
echo "<li align='left'>" . "<b><font color='$color'>Private from: $author</font></b>" . "<b><font color='$color'> - </font></b>" . "<font color='$color'>$message</font><hr>";}
}else{
echo "<li align='left'>" . "<b><font color='$color'>$author</font></b>" . "<b><font color='$color'> - </font></b>" . "<font color='$color'>$message</font><hr>";
}}
mysqli_close($con);
echo '</ul>';
echo '</div>';
}else{
echo 'You are not logged!';
}
?>
Where the main form goes (MySQL connection details have been removed):
<?php
session_start();
$conn = new mysqli('', '', '', '');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(IsSet($_POST['text']) && ($_POST['text']) != ''){
if($_POST['private'] == 'public'){
$nick = $_SESSION['nick'];
$text = $_POST['text'];
$time = date('c');
$color = $_SESSION['color'];
$text = mysqli_real_escape_string($conn,$text);
$sql = "INSERT INTO chat (author, message, time, color, p, PRIVATE)
VALUES ('$nick', '$text', '$time', '$color', '0', '')";
if ($conn->query($sql) === TRUE) {
header('Location: /chat/chat.php');
} else {
echo "Error";
}
$conn->close();
}else{
$nick = $_SESSION['nick'];
$text = $_POST['text'];
$time = date('c');
$color = $_SESSION['color'];
$destinatary = $_POST['private'];
$text = mysqli_real_escape_string($conn,$text);
$sql = "INSERT INTO chat (author, message, time, color, p, PRIVATE)
VALUES ('$nick', '$text', '$time', '$color', '1', '$destinatary')";
if ($conn->query($sql) === TRUE) {
header('Location: /chat/chat.php');
} else {
echo "Error";
}
$conn->close();
}}else{
header('Location: /chat/chat.php');
}
?>

Related

How can I show the correct answer of an entry on the page itself?

I'm making a quiz. I displayed Q/A from db and the correct answer. How to see the answer of the specific question on clicking the Check Answer button.
<?php
if (isset($_GET['pageno'])){
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 1;
$offset = ($pageno - 1) * $no_of_records_per_page;
$conn = mysqli_connect("localhost", "root", "", "quizdb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$total_pages_sql = "SELECT COUNT(*) FROM entry1";
$result = mysqli_query($conn, $total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
$sql = "SELECT * FROM entry1 LIMIT $offset, $no_of_records_per_page";
$res_data = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($res_data)) {
include('server1.php');
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'quizdb';
$con = mysqli_connect($host, $user, $pass, $db);
$qno = $row["qno"];
$question = $row["question"];
$optiona = $row["optiona"];
$optionb = $row["optionb"];
$optionc = $row["optionc"];
$optiond = $row["optiond"];
$ans = $row["ans"];
echo '<br>Q ' . $qno . '. ';
echo '' . $question . '<br>';
echo '<input type="radio" name="options" value="optiona"></button>' . $optiona . '<br>';
echo '<input type="radio" name="options" value="optionb"></button>' . $optionb . '<br>';
echo '<input type="radio" name="options" value="optionc"></button>' . $optionc . '<br>';
echo '<input type="radio" name="options" value="optiond"></button>' . $optiond . '<br>';
echo '<form action="practice.php" method="post">
<input type="submit" name="submitans" value="Check Answer"></form>';
if (isset($_POST['submitans'])) {
echo '' . $ans . '<br>';
}
}
mysqli_close($conn);
?>
<ul class="pagination">
<li>First</li>
<li class="<?php if ($pageno <= 1) {
echo 'disabled';
} ?>">
<a href="<?php if ($pageno <= 1) {
echo '#';
} else {
echo "?pageno=" . ($pageno - 1);
} ?>">Prev</a></li>
<li class="<?php if ($pageno >= $total_pages) {
echo 'disabled';
} ?>">
<a href="<?php if ($pageno >= $total_pages) {
echo '#';
}
else {
echo "?pageno=" . ($pageno + 1);
} ?>">Next</a>
</li>
<li>Last</li>
</ul>
</body>
</html>
Expected Result - When I click next and I see another question, I click on Check Answer, then I see the answer of that question.
Actual Result - When I click next and I see another question, I click on Check Answer, then I go back to the first page and its answer is shown

Search in PHP not showing message when there's no result

I had set a search button in my website. It works fine if there's a result but if there's none, it doesn't show the "no results.....".
What's wrong with my code?
<html !DOCTYPE HTML>
<body>
<?php
$title = "DenTEETH";
include('header.html');
//connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "authentication");
if(isset($_GET['q']) && $_GET['q'] !== '')
{
$searchq = $_GET['q'];
$sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
$output='';
$results = mysqli_query($db, $sql);
if (count($results) == 0){
$output .= 'No search results for <b>"' . $searchq . '"</b>';
}
else{
while ($row = mysqli_fetch_array($results)){
$id = $row['search_id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';
$output .= '<div class="search_thumb">
<p class="search_cap">' . $img . '<h3>' . $title . '</h3>' . $desc .
'<div class="clear"></div></p></div>';
}
}
}
else{
header("location: ./");
}
print($output);
?>
<div class="row">
</div>
<?php
include('footer.html');
?>
</body>
</html>
Use mysqli_num_rows() try this
<html !DOCTYPE HTML>
<body>
<?php
$title = "DenTEETH";
include('header.html');
//connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "authentication");
if(isset($_GET['q']) && $_GET['q'] !== '')
{
$searchq = $_GET['q'];
$sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
$output='';
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results ) == 0){
$output .= 'No search results for <b>"' . $searchq . '"</b>';
}
else{
while ($row = mysqli_fetch_array($results)){
$id = $row['search_id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';
$output .= '<div class="search_thumb">
<p class="search_cap">' . $img . '<h3>' . $title . '</h3>' . $desc .
'<div class="clear"></div></p></div>';
}
}
}
else{
header("location: ./");
}
print($output);
?>
<div class="row">
</div>
<?php
include('footer.html');
?>
</body>
</html>

How can I make my submit button add the values to my cart table

I'm trying to get the "Cart_View02" table to update when the submit button is clicked. I'm new to php and sql this semester. Anybody know what I'm doing wrong?
<?PHP
if (isset($_GET['tab'])) $table= $_GET['tab'];
else $table="Cart_view02";
$reset = true;
$errmsg = array("","");
//1. Make a connection to the database
$dbconn = mysqli_connect("localhost","root","","mydatabase1")
or die(mysqli_connect_error());
if($_SERVER['REQUEST_METHOD']=='POST'){
$action = $_POST['action'];
$qty = $_POST['txtqty'];
$crtnum = $_POST[100];
$itemid = $_POST[$row[0]];
if($action == "select"){
$sql = "INSERT INTO cart_lineitems VALUES ($crtnum, '$itemid',
'$qty');";
$result = mysqli_query($db,$sql) or die(mysql_error($db));
}
//print_r($_POST);
header("location: cartdump.php");
}
?>
<!DOCTYPE html>
<html>
<head><title>Order Page</title>
<link href="css/styles.css" type="text/css" rel="stylesheet" />
<script type="text/javascript">
</script>
<img class="banner" src="Images/acme_banner.jpg" alt="Acme Spook Shoppe"/>
</head>
<body>
<br><br>
Home
<form name="form1" method='POST'>
<?php
if (isset($_GET['prod'])) $prod=$_GET['prod'];
else $prod = "arm01";
//echo $prod; //<------To print results
$sql = "select productid,name,imagefile, "
."shortdescription, longdescription,"
."unitprice "
."from products "
."where productid='$prod'";
echo "<br>";
//echo $sql; //<------To print results
//2. Run a query against the database
$result = mysqli_query($dbconn,$sql)
or die(mysqli_error($dbconn));
//print_r($result); //<------To print results
//3. Return the results
echo "<table class=ordertable >";
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>$row[1]<br><br>";
echo "$row[3]<br><br>";
echo "$row[4]<br><br>";
echo "Price: $row[5]<br><br>";
echo "<input type='text' name='txtqty' value='1' size=2 maxlength=2>";
echo "<input type='submit' name='btnadd' value='Add To Cart'
OnClick='SubmitForm'>";
echo "</td>";
echo "<td><img src='images/products/$row[2]' "
."height=300px width =250px></td>";
echo "</tr>";
echo "</table>";
//print_r($row);
}
//4. Release the resources
mysqli_free_result($result);
//5. Close the connection
mysqli_close($dbconn);
?>
</form>
</body>
</html>
Any help on this would be greatly appreciated.
This is what I ended up with:
<!DOCTYPE html>
<?PHP
print_r($_POST);
if (isset($_GET['prod'])) $prod=$_GET['prod'];
else $prod = "arm01";
//if (isset($_GET['tab'])) $table= $_GET['tab'];
// else $table="Cart_view02";
//$reset = true;
//$errmsg = array("","");
//1. Make a connection to the database
$dbconn = mysqli_connect("localhost","root","","mydatabase1")
or die(mysqli_connect_error());
if($_SERVER['REQUEST_METHOD']=='POST'){
$qty = $_POST['txtqty'];
$crtnum = 100;
if (preg_match("/^[0-9]{1,2}$/",$qty)){
$sql = "INSERT INTO cart_lineitems VALUES ($crtnum, '$prod', $qty);";
$result = mysqli_query($dbconn,$sql) or die(mysqli_error($dbconn));
//echo"<br>$sql";
header("location: cartdump.php");
}
else echo "Quantity is not valid<br>";
}
?>
<html>
<head><title>Order Page</title>
<link href="css/styles.css" type="text/css" rel="stylesheet" />
<script type="text/javascript">
</script>
<img class="banner" src="Images/acme_banner.jpg" alt="Acme Spook Shoppe"/>
</head>
<body>
<br><br>
Home
<form name="form1" method='POST'>
<?php
//echo $prod; //<------To print results
$sql = "select productid,name,imagefile, "
."shortdescription, longdescription,"
."unitprice "
."from products "
."where productid='$prod'";
echo "<br>";
//echo $sql; //<------To print results
//2. Run a query against the database
$result = mysqli_query($dbconn,$sql)
or die(mysqli_error($dbconn));
//print_r($result); //<------To print results
//3. Return the results
echo "<table class=ordertable >";
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>$row[1]<br><br>";
echo "$row[3]<br><br>";
echo "$row[4]<br><br>";
echo "Price: $row[5]<br><br>";
echo "<input type='text' name='txtqty' value='1' size=2 maxlength=2>";
echo "<input type='submit' name='btnadd' value='Add To Cart' OnClick='SubmitForm'>";
echo "</td>";
echo "<td><img src='images/products/$row[2]' "
."height=300px width =250px></td>";
echo "</tr>";
echo "</table>";
//print_r($row);
}
//4. Release the resources
mysqli_free_result($result);
//5. Close the connection
mysqli_close($dbconn);
?>
</form>
</body>
</html>

search and pagination not work

hello I try to combine the two scripts from the book PHP 6 and MySQL 5 for Dynamic Web Sites. I did search and pagination, but when I go to the next page - did not work.
I posted two screenshots below.
if someone could show me how I make a mistake I will be grateful.
<?php require_once("../../includes/functions_2.php"); ?>
<?php
//database connect
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1qazxsw2";
$dbname = "dw_bookstore";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//sprawdzenie polaczenia
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//zmaiana znako na utf8
if (!mysqli_set_charset($connection, "utf8")) {
printf("Error loading character set utf8: %s\n", mysqli_error($connection));
} else {
//printf("Kodowanie ustawione na: %s\n", mysqli_character_set_name($connection));
}
?>
<?php
// Number of records to show per page:
$display = 3;
// Determine how many pages there are...
if (isset($_GET['p']) && is_numeric($_GET['p'])) { // Already been determined.
$pages = $_GET['p'];
} else { // Need to determine.
#$query = $_GET['query'];
$query4 = "SELECT COUNT(id) ";
$query4 .= "FROM photographs ";
$query4 .= "WHERE `nazwa` LIKE '%".$query."%' ";
//$query .= "WHERE visible = 1 ";
$result = #mysqli_query ($connection, $query4);
$row = #mysqli_fetch_array ($result, MYSQLI_NUM);
$records = $row[0];
// Count the number of records:
if ($records > $display) { // More than 1 page.
$pages = ceil ($records/$display);
} else {
$pages = 1;
}
} // End of p IF.
// Determine where in the database to start returning results...
if (isset($_GET['s']) && is_numeric($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
// Make the query:
#$query = $_GET['query'];
$query3 = "SELECT * ";
$query3 .= "FROM photographs ";
$query3 .= "WHERE `nazwa` LIKE '%".$query."%' ";
$query3 .= "OR `kod` LIKE '%".$query."%' ";
//$query .= "AND visible = 1 ";
$query3 .= "ORDER BY id ASC LIMIT $start, $display ";
$result3 = mysqli_query ($connection, $query3);
?>
<?php
// 2. Perform database query
$query2 = "SELECT * ";
$query2 .= "FROM photographs ";
//$query2 .= "WHERE visible = 1 ";
$query2 .= "ORDER BY nazwa ASC ";
$result2 = mysqli_query($connection, $query2);
// Test if there was a query error
if (!$result2) {
die("Database query failed.");
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>List_n01</title>
<link href="../../stylesheets/main_2.css" rel="stylesheet" type="text/css" media="screen, projection" />
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>Cennik: Panel Administracyjny</h2>
</div>
<div id="mainContent">
<h1>Graphic Design</h1>
<?php
// Count the number of returned rows:
$num = mysqli_num_rows($result2);
if ($num > 0) { // If it ran OK, display the records.
// Print how many rows there are:
echo "<p>W bazie znajduje się $num pozycji.</p>\n"; ?>
<form action="<?php echo $_SERVER ['PHP_SELF']; ?>" method="GET">
<fieldset>
<ul class="formList">
<li>
<input type="text" name="query" placeholder="Szukana fraza... " />
<input type="submit" value="Search" />
</li>
</fieldset>
</form>
<table id="article">
<caption></caption>
<colgroup>
</colgroup>
<tr>
<th>Zdjęcie:</th>
<th>Typ:</th>
<th>Wielkość:</th>
<th>Nazwa:Nazwa:</th>
<th>Kod:</th>
<th>Edytuj:</th>
<th>Szczegóły:</th>
<th>Usuń:</th>
</tr>
<?php
// 3. Use returned data (if any)
while($row = mysqli_fetch_assoc($result3)) {
// output data from each row
?>
<tr>
<td><img src="../images/<?php echo $row['filename']; ?>" width="150" class="article" /></td>
<td><?php echo $row['type']; ?></td>
<td><?php echo size_as_kb($row['size']); ?></td>
<td><?php echo $row['nazwa']; ?></td>
<td><?php echo $row['kod']; ?></td>
<td>Edytuj</td>
<td>Detale</td>
<td>{Usuń}</td>
</tr>
<?php
}
?>
</table>
<?php
// 4. Release returned data
mysqli_free_result($result3);
} else { // If no records were returned.
echo '<p class="error">There are currently no rows.</p>';
}
?>
<?php
// Make the links to other pages, if necessary.
if ($pages > 1) {
echo '<br /><p>';
$current_page = ($start/$display) + 1;
// If it's not the first page, make a Previous button:
if ($current_page != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
$distance = $current_page - $i;
if (abs($distance) < 5){
echo '' . $i . ' ';
}
} else {
echo $i . ' ';
}
} // End of FOR loop
// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}
echo '</p>'; // Close the paragraph.
} // End of links section.
?>
</div>
<div id="footer">
<p>Copyright <?php echo date("Y", time()); ?>, Cleoni</p></div>
</div>
</body>
</html>
<?php
// 5. Close database connection
mysqli_close($connection);
?>
you are facing issues because in your second url, the query parameter is missing, you should have also have the query=car parameter in get as the data that is been searched is searched with that parameter according to the script...
Change code from around line 184-204 to the following
// If it's not the first page, make a Previous button:
if ($current_page != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
$distance = $current_page - $i;
if (abs($distance) < 5){
echo '' . $i . ' ';
}
} else {
echo $i . ' ';
}
} // End of FOR loop
// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}

MySQL/PHP News System

I have a PHP/MySQL News system which displayes the newest news article on the home page and a full list on a news page.
The newest article bit works but, my problem is that whenever i try to echo all the news article on the news page it either repeats the same or outputs one and nothing else.
**MySQL Information**
id INT AUTO_INCREMENT,
author VARCHAR(xxx),
title VARCHAR(xxx),
message TEXT,
date TEXT,
time TEXT,
PRIMARY KEY(id)
This is the insertion page (news_center.php)
<form action='/?module=admin&n=news_center_ac' method='post'>
<table align="center" width="68%">
<tr>
<td>Title</td>
<td><input style="width:100%;" type='text' name='news_title' /></td>
</tr>
<tr>
<td height="57">Message</td>
<td><input style="width:100%; height:100%;" type='text' name='news_message' /></td>
</tr>
<tr>
<td colspan='2'><input type='submit' /></td>
</tr>
</table>
This is news_center_ac.php
<?php
$conn = mysql_connect(*Connection Information*) or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$author == $_SESSION['name'];
if(!empty($_POST['news_title']) || !empty($_POST['news_message']))
{
if(!empty($_POST['news_title']) && !empty($_POST['news_message']))
{
$date = date( 'jS F Y' );
$time = date( 'H:i' );
$query = "INSERT INTO news (id, author, title, content, date, time) VALUES('', '".$author."', '".$_POST['news_title']."', '".$_POST['news_message']."', '".$date."', '".$time."')" or die(mysql_error());
$insert = mysql_query($query) or die(mysql_error());
echo '<p>Successful News Update “'.$_POST['news_title'].'”';
}
else
{
echo '<p>Please fill in all fields</p>';
}
}
?>
This is the Output on the news page (/news/index.php)
<?php
$conn = mysql_connect("*CONNECTION INFORMATION*") or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$news = mysql_query("SELECT * FROM news ORDER BY date DESC,id DESC");
$output = mysql_fetch_array($news);
?>
*CONTENT*
<?php
foreach ($output as $value) {
echo "<p> “" .$output['content'];
echo "”";
echo "Posted:" .$output['date'];
echo " " .$output['time'];
}
?>
I just want it to output each news article in turn i can sort out the formatting later once it works.
You are misusing mysql_fetch_array(). It needs to be called in a loop, as it only returns one row at a time.
$conn = mysql_connect("*CONNECTION INFORMATION*") or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$news = mysql_query("SELECT * FROM news ORDER BY date DESC,id DESC");
EDIT Added htmlentities() calls to convert html special characters
while ($row = mysql_fetch_array($news)) {
echo "<p> “" . htmlentities($row['content']);
echo "”";
echo "Posted:" . htmlentities($row['date']);
echo " " . htmlentities($row['time']);
}
Rewrite it this way:
<?php
while($output = mysql_fetch_array($news)) {
echo "<p> “" .$output['content'];
echo "”";
echo "Posted:" .$output['date'];
echo " " .$output['time'];
}
?>
When you call output first, it is only returning one value, this will loop through all.
try /news/index.php
<?php
$conn = mysql_connect("*CONNECTION INFORMATION*") or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$news = mysql_query("SELECT * FROM news ORDER BY date DESC,id DESC");
while($output = mysql_fetch_assoc($news)) {
echo "<p> “" .$output['content'];
echo "”";
echo "Posted:" .$output['date'];
echo " " .$output['time'];
}
?>
Shouldn't the last foreach loop use $value, ie
<?php
foreach ($output as $value) {
echo "<p> “" .$value['content'];
echo "”";
echo "Posted:" .$value['date'];
echo " " .$value['time'];
}
?>

Categories