when displaying records its duplicating on page refresh? - php

my code looks like this
when I refresh the page it's duplicating the last value how to avoid this problem. This is the quoa.php code! I have tried adding distinct but its working fine but there is no use problem still on there?
phpcode
<?php
/* connection inclution code will be here */
include 'connection/conn.php';
//defining the variables to the text fields
$question = $_POST['qst'];
$questionext = $_POST['qsttextarea'];
//validating the text fields , if there is no text show the msg after else
if(isset($_POST['qst']) && isset($_POST['qsttextarea']))
{
} else {
$pleasefill = "please fill all the fields";
}
//sending data to the database
$mysqlinsert = "INSERT INTO questions(qsttable,qstext) VALUES ('$question','$questionext')";
//header("Location: success.php");
if (!mysqli_query($connection,$mysqlinsert)) {
echo " record not inserted";
} else {
$submited = (" your question is submited please wait for the response");
}
//getting data from the database
if ($data = mysqli_query($connection,"select distinct * from questions")); {
}
?>
show record code
<?php
while($row=mysqli_fetch_array($data)) {
echo '
<div id="question_div"> <span class="fa fa-chevron-right" id="spantick"></span> '.''.$row['qsttable'].' <br />'.'<p id="qstext">'.$row['qstext'].' </p> </div> ' ;
}echo ' Read more ';
?>

You should perform html validation in your input fields ,in that way when you refresh the page all the fields will be empty and previous values will not be stored.
Just add 'required' keyword in your fields ,that will do.
eg.

Related

How to remove a row from MySQL table data using html delete button in PHP

I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}

POST Data not inserting into sql table

I am using a form. (I wanted the message text as a text area but changed back to normal text to see if this was the problem)
This is the form I am using
<form name="addmessage" method="POST" action="addmessage.php" >
<input type="text" name="message_title" id="message_title">Message Title</input>
<input type="text" name="message_text" id="message_text">Message</input>
<input type="submit" name="submit" value = Add>
</form>
Below is the PHP code. I understand i need to protect against sql injection however, i can do this later.
<?php
include_once("config.php");
if(isset($_POST["message_title"]) && strlen($_POST["message_title"])>0)
{
$message_title=$_POST['message_title'];
$message_text=$_POST['message_text'];
session_start();
$barber_id = $_SESSION['barber_id'];
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
}
else
{
//Output error
header('HTTP/1.1 500 Error You have left it blank');
exit();
}
header("location:messages.php");
?>
If manually enter data using phpMyAdmin, I can get it to display using the code below.
include_once("config.php");
session_start();
$barber_id = $_SESSION['barber_id'];
$results = $mysqli->query("SELECT * FROM messages WHERE barber_id ='$barber_id' ");
//get all records from table
while($row = $results->fetch_assoc())
{
$prices_id = $row['prices_id'];
echo '<div data-role="collapsible">';
echo '<h1>';
echo ' Message Title: ';
echo $row['message_title'];
echo '</a>';
echo '</h1>';
echo '<p>';
echo $row['message_text'];
echo ' Delete</div>';
}
$mysqli->close();
?>
At $insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
you should write
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."','".$message_text."')");
Everytime you pass a String or other non int values you must pass them like that: 'xx', otherwise mysql will see it as query param and it crashes.

Data not going into my sql database from php code on webpage

guys i want to submit data from text boxes ect to my database .. i have kept a pop up box to say submitted ..into database .. and when i execute it says entered database but the database is empty..
<?php
include('airlineDB2.php');
$nameb1 = #$_POST['nameb1'];
$ageb1 = #$_POST['ageb1'];
$genderb1 = #$_POST['genderb1'];
$prefb1 = #$_POST['prefb1'];
$planeno = #$_POST['planeno'];
$pdate = #$_POST['pdate'];
if (isset($_POST['book'])) {
//The data is entered into the database here between this
$insert = mysql_query("Insert into ticketbook (planeno,nameb,ageb,genderb,preferenceb,date) VALUES('$planeno','$nameb1','$ageb1','$genderb1','$prefb1','$pdate')");
echo '<script type="text/javascript">alert("Your ticket is booked check your email for further details!")</script>';
//The data is entered into the database here between this
}
?>
There is some error with your query, you can change the logic to this:
$insert = mysql_query("Insert into ticketbook (planeno,nameb,ageb,genderb,preferenceb,date) VALUES('$planeno','$nameb1','$ageb1','$genderb1','$prefb1','$pdate')");
if ( !$insert ) {
die('Invalid query: ' . mysql_error());
} else if ( mysql_affected_rows()!=1 ) {
die('Error inserting row');
} else {
echo '<script type="text/javascript">alert("Your ticket is booked check your email for further details!")</script>';
};

Error messages with different situations while saving to database with php form

i have a script that saves records to mysql with no problem. but i want to add some code to show an error message if the name or code already exists in the database. the code is like below;
<?php
$urunadi = $_POST["urunadi"];
$malzemekodu = $_POST["malzemekodu"];
$urunkategorisi = $_POST["urunkategorisi"];
$birim = $_POST["birim"];
$miktar = $_POST["miktar"];
$personel = $_POST["personel"];
$birimfiyat = $_POST["birimfiyat"];
$toplamfiyat = $_POST["birimfiyat"]*$_POST["miktar"];
$fiyatbirimi = $_POST["fiyatbirimi"];
if(empty($urunadi)){
echo("<center><b>Product name empty, please go back and fill this line.</b></center>");
}else
if(empty($miktar)){
echo("<center><b>Product amount empty, please go back and fill this line.
}else
if(empty($malzemekodu)){
echo("<center><b>Product code empty, please go back and fill this line.</b></center>");
}else
if(empty($birimfiyat)){
echo("<center><b>Unit price empty, please go back and fill this line.</b></center>");
}else{
include "database.php";
$sql = (" insert into `depo` (`urunadi`,`malzemekodu`,`urunkategorisi`,`birim`,`miktar`,`personel`,`birimfiyat`,`toplamfiyat`,`fiyatbirimi`)
VALUES ('$urunadi','$malzemekodu','$urunkategorisi','$birim','$miktar','$personel','$birimfiyat','$toplamfiyat','$fiyatbirimi');");
$kayit = mysql_query($sql);
}
if (isset ($kayit)){
echo "<center>Data saved</center>";
}
else {
echo "<center>Data could not be saved</center>";
}
if (isset($_REQUEST["kullanici"])) {
include("database.php");
$sql = ("select * from uye");
}
else {
header ("Location: uyari.html");
}
?>

PHP Basics - Echo messages in a redirected page

I have a website, which you press a button and a popup DIV loads up.
On this DIV is a JQuery Validator form which submits to a separate PHP file.
The PHP logins to a database through MySQLi and adds a user. Whilst it does it, at each stage it does an echo message (the idea is that I know what its doing).
This leaves me with a white screen with several lines of information. Its fantastically useful but very ugly from the nice popup div registration.
Is there any way, at the end of the PHP it can redirect to another page assuming there was a blank div in it where the echo information can go, and I can jazz the remaining page up with HTML5 and CSS.
If so how do I get the echo messages into this div?
Thanks
Please see the snippet (which is working) below - but go easy on me as its only been a couple of weeks of learning.
function webmailSignUp($db_connection,$db_con_table) //The function for the website REGISTER FORM
{
$webmailFullName = $_POST['webmailFullName'];
$webmailUserName = $_POST['webmailUserName'];
$webmailExEmail = $_POST['webmailExEmail'];
$webmailPhone = $_POST['webmailPhone'];
$webmailDOB = $_POST['webmailDOB'];
//Check that the fields are not empty
if (checkBlankFieldsError($webmailFullName,$webmailUserName,$webmailExEmail,$webmailPhone,$webmailDOB) == false)
{
echo "There are no empty Form Input Fields<br>";
//Connecting to MySQL
if (mysqli_connect_errno($db_connection))
{
echo "Failed to connect to MySQL database:" . mysqli_connect_error();
echo "<br>";
}
else
{
echo "Connected to database<br>";
//Check that there is no existing name in the table
if (checkInField($webmailUserName,$db_connection,$db_con_table,"userName") == false)
{
//Check DOB Field
$dob = $webmailDOB; //or use for non-iso: convertDate($webmailDOB);
echo "DOB is: $dob<br>";
//Binding and Query to prevent SQL injection
$query = "INSERT INTO $db_con_table(userFullName,userName,userExEmail,userPhone,userDOB) VALUES(?,?,?,?,?)";
$requery = $db_connection->prepare($query);
$requery->bind_param("sssss",$webmailFullName,$webmailUserName,$webmailExEmail,$webmailPhone,$dob);
if ($requery->execute())
{
echo "$webmailUserName has been added to the Webmail Database<br>";
}
else
{
echo "bind failed on $webmailUserName <br>";
}
//Close Database
$db_connection->close();
echo "Database is Closed.<br>";
}
else{echo "There is already a user registered with this username. Please try a different one.<br>";}
}
}
else
{
echo "There is 1 or more empty input fields. Please try again.<br>";
}
}
function checkInField($value,$db_connection,$db_con_table, $db_field) // Checks a value is not within a database field
{
$query = "SELECT $db_field FROM $db_con_table WHERE $db_field='$value'";
$result = $db_connection->query($query) or die($mysqli->error());
// GOING THROUGH THE DATA
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo "User $value found: '$row[$db_field]' in the table $db_con_table column $db_field<br>";
return true;
}
}
else
{
echo "User $value has not been found in the table $db_con_table column $db_field<br>";
return false;
}
}
function checkBlankFieldsError($field1,$field2,$field3,$field4,$field5) //Checks if form fields are blank
{
$fields = array($field1,$field2,$field3,$field4,$field5);
$error = false;
foreach($fields AS $fieldname) //Loop trough each fieldname in the fields array
{
if(empty($fieldname))
{
$error = true;
}
else
{
}
}
return $error;
}
function convertDate($aString) //Converts a String to a Date in Y-M-D format
{
$date2 = DateTime::createFromFormat('m/d/Y', $aString);
return $date2->format('Y-m-d');
}
//Main Code Sequence on form buttons
if(isset($_POST['webmailRegisterSubmit']))
{
webmailSignUp($mysqli_db,$db_table);
echo "End of Registration.<br>";
}
if(isset($_POST['webamilForgottenPWSubmit']))
{
webmailForgottenPassword();
echo "End of Password Reset Request.<br>";
}
If you really want a redirection, you will have to store your messages somewhere. I suggest you to save them in the user session. The workflow would be :
user do action (save form / get page : anything)
server treat the request and store a new "message" in a specific array in the user session (standard php $_SESSION) depending on the situation (error message ? success message ?). At this point you should store the message and its level (INFO/WARNING/ERROR/SUCCESS/etc)
server do a rediction (if needed)
create a method which :
retrieve all store message and delete them directly cause you want to display them only once
display them on your DIV
you're done
The good thing with this worklow is that it will work even without a redirection as you separate clearly messages addition/storing and display.
Hope this helps

Categories