Unable to go to next page after successfully added data to database - php

Currently, I do the room booking. My scenario is after I added data and click the add button, it cannot redirect to the next page it stick with the same page. My current page is add_factory.php
Same goes happen when the data insert is duplicated, the alert message doesn't appear although I create the alert js.
Below is my current PHP code.
<?php
require_once "../../config/configPDO.php";
require_once "../../config/check.php";
if(isset($_POST['Submit']))
{
//Getting Post Values
$Fac_ID = $_POST['Fac_ID'];
// Query for validation of username and email-id
$ret="SELECT * FROM factory where (Fac_ID=:Fac_ID)";
$queryt = $conn -> prepare($ret);
$queryt->bindParam(':Fac_ID',$Fac_ID,PDO::PARAM_STR);
$queryt -> execute();
$results = $queryt -> fetchAll(PDO::FETCH_OBJ);
if($queryt -> rowCount() == 0)
{
// Query for Insertion
$sql="INSERT INTO factory(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_ID)";
$query = $conn->prepare($sql);
// Binding Post Values
$query->bindparam(':Fac_Name', $Fac_ID);
$query->bindparam(':Fac_ID', $Fac_ID);
$query->execute();
$lastInsertId = $conn->lastInsertId();
if($lastInsertId){
header("Location:factory.php");
}else{
echo "
<script>alert('Something wrong, please try again')</script>
<script>window.location = 'factory.php'</script>
";
}
}
else{
echo "
<script>alert('The factory you add is already exist')</script>
<script>window.location = 'factory.php'</script>
";
}
}
?>
this is my form
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<table width="90%">
<tr>
<td width="20%"><b>Factory Name</b></td>
<td width="50%"><input type="text" onkeyup="this.value = this.value.toUpperCase();" class="form-control" name="Fac_ID" required></td>
</tr>
</table>
<br>
<input type="submit" name="Submit" value="Add" class="btn btn-primary btn-block" onclick="return confirm('Do you want to add this factory?');">
</form>
Can anyone know how to solve?

First of all
it cannot redirect to the next page it stick with the same page
it's because of this, it will load in the same page:
header("Location:factory.php");
and this:
window.location = 'factory.php'
Second,the duplicate alert won't appear because the page itself is already loading in factory.php
So change your code from:
echo "
<script>alert('The factory you add is already exist')</script>
<script>window.location = 'factory.php'</script>
";
to:
echo "
<script>alert('The factory you add is already exist');
window.open("factory.php", "_blank");</script>
";
The window.open("factory.php", "_blank"); means it will redirect to other page, not on the same page.
Lastly, don't forget to add ; to every statement

Related

Value not saving after form is submitted

I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// 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);
}
?>

Indicate the newly added user with different color or symbol or div highlighting

I want to indicate the currently newly added user through symbol or unique color, like when someone click on Save and the user that is added should be shown in a different color or highlighted at that glimpse and then disappear after refresh, something like what the stackoverflow does in commenting system.
This is my code of index.php in this page I'v form and after submitting this form I' added the user to the database and then I'v shown them in descending order
<form action="save.php" method="post">
<div class="text-center" id='input_tag'>
<input type="text" name="name" id= 'input'>
<input type="submit" name="submit" class="btn btn-dark " id = "button" value="Save">
</div>
</form>
<div class="container">
<div class="row">
<div class="col-md-4">
<table width="100" class="table" id = 'tb'>
<?php
$connect = mysqli_connect('localhost','root','root','user');
$query = "SELECT name from userdata order by id DESC";
$run = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($run))
{
echo "<tr>";
echo "<td>".$row['name']."<td>";
echo "</tr>";
}
?>
</table>
</div>
</div>
</div>
This is save.php where the user are added to DB and then redirected to the index.php page
$connect = mysqli_connect('localhost', 'root' ,'root' ,'user');
if($connect){
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$query = "INSERT INTO `userdata`(`name`) values ('$name')";
if(mysqli_query($connect,$query)){
header('location:index.php');
}
}
}
else{
echo "not connected";
}
You can achieve this with simple CSS and JS.
Change the header function in save.php to
header('location:index.php?added=1');
Add CSS style to index.php
<style type="text/css">
tr:last-of-type {
transition: .7s background;
}
</style>
At the end of index.php add the following
<?php
if (isset($_GET['added'])){
print '<script type="text/javascript">
document.querySelector("tr:first-of-type").style.background = "red";
setTimeout(function() {document.querySelector("tr:first-of-type").style.background = unset"},2000);
</script>';
}
?>
I'm assuming that the new user is going to be displayed at first.
If you want to display the user differently the first time, then you will need
some sort of flag that says if the user has been shown yet or not.
At the time you insert the user, set the didShow flag to false.
When you show the user, check the flag and if false, show the user
with the symbol and set the didShow flag to true.
When you show the user, if the didShow flag is false, show the
user without the symbol.
Add a new column named didShow to your database. Set it to default to 0 (false).
Change the query like this:
$query = "SELECT id, name, didShow from userdata order by id DESC";
In the loop, use different formatting and update the rows that have to be updated.
$run = mysqli_query($connect, $query);
$style = 'style="color:#ccc"';
while($row = mysqli_fetch_array($run))
{
echo "<tr>";
if ( $row['didShow'] == 0 ) {
echo "<td><span {$style}>".$row['name']."</span><td>";
$updateQuery = "UPDATE `userdata` SET didShow=1 WHERE id = {$row['id']}";
mysqli_query($connect, $updateQuery);
} else {
echo "<td>".$row['name']."<td>";
}
echo "</tr>";
}

Using $_GET outside the while loop in which [''] is defined

For example, I have the following code:
<?php
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' ORDER BY id DESC");
while ($row = mysqli_fetch_array($query)) {
$thought_id = $row['id'];
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
// for each post a user has made, a new div will be echo's
echo "
<div class='message_wrapper'>
// all content here which displays the message and author.
// consider this anchor link, and see $_GET approach below.
<a href='/inc/del_post.php?id=$thought_id>'>Delete </a>
<div id='toggleComment$thought_id' class='new_comment'>
<form action='' method='post' enctype='multipart/form-data'>
<table>
<tr>
<td>
<textarea id='txtarea' name='comment_msg' cols='80' maxlength='180' placeholder=' add your comment...'></textarea>
</td>
<td>
<input id='send' type='submit' name='send_comm' value='Share'/>
</td>
</tr>
</table>
</form>
</div>
</div>";
} // while loop closed
// sending comments to database
$comment = htmlentities(trim(strip_tags(#$_POST['comment_msg'])));
$comment = mysqli_real_escape_string($connect, $comment);
// if button is pressed, do this...
if(isset($_POST['send_comm'])){
if (!empty ($comment)){
$insert_comment = mysqli_query ($connect, "INSERT INTO user_comments VALUES ('','$comment','$username','$user','0','$thought_id')");
header ("Location: /profile_page/$user");
}
}
?>
Before, I had the 'send_comm' processing in the while loop, and when I use to submit the form, the comment would be added to all of a users posts. For example, Alice has made two posts, I add a comment to one, both posts will display that message (and two new rows in db).
Now, to fix the above issue, I have put the 'send_comm' processing, outside the while loop,but of course, with this $thought_id (which in in my INSERT) would be undefined. Also, having it outside the while loop provides no way of the comment knowing which thought_id is is assigned to. So to fix this, I tried to use $_GET:
$thought_id_from_anchor = $_GET ['id'];
// if button is pressed, do this...
if(isset($_POST['send_comm'])){
if (!empty ($comment)){
$insert_comment = mysqli_query ($connect, "INSERT INTO user_comments VALUES ('','$comment','$username','$user','0','$thought_id_from_anchor')");
header ("Location: /profile_page/$user");
}
}
But of course, since it is outside the while loop, I get an undefined error on id.
I just need a comment to be added to the $thought_id it is being added to.
You can simply add a hidden input to your form containing the value of $thought_id:
<form action='' method='post' enctype='multipart/form-data'>
<input type='hidden' name='thought_id' value='$thought_id'>
<table>
<tr>
<td>
<textarea id='txtarea' name='comment_msg' cols='80' maxlength='180' placeholder=' add your comment...'></textarea>
</td>
<td>
<input id='send' type='submit' name='send_comm' value='Share'/>
</td>
</tr>
</table>
</form>
Then when the form is submitted, you can access the value of thought_id using $_POST for your query (also cleaned it up a bit):
// if button is pressed, do this...
if (isset($_POST['send_comm'])) {
$_POST = array_map('trim', $_POST);
if (!empty($_POST['thought_id']) &&
!empty($_POST['comment_msg'])) {
$comment = htmlentities(strip_tags($_POST['comment_msg']));
$comment = mysqli_real_escape_string($connect, $comment);
$thought_id = mysqli_real_escape_string($connect, $_POST['thought_id']);
$insert_comment = mysqli_query ($connect, "INSERT INTO user_comments VALUES ('','$comment','$username','$user','0','$thought_id')");
header ("Location: /profile_page/$user");
}
else {
// empty fields; handle this accordingly
}
}
INSERT INTO user_comments VALUES ('','$comment'
What is that empty string?
I think that is the ID, so, IDs only accepts integer values, you can replace by null, or remove it.
INSERT INTO user_comments VALUES (null,'$comment'
INSERT INTO user_comments VALUES ('$comment'
if you want to use the id out side of the loop you will have to assing it >to a global variable.You will need to declare a variable in the global scope >and then use the global keyword with in the while loop. Once you do this you can use the thought_id variable any were you choose.
<?php
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' ORDER BY id DESC");
$thought_id; // Declare the variable outside of the while loop in the global scope
while ($row = mysqli_fetch_array($query)) {
global $thought_id = $row['id'];
/*use the global keyword to assign the the value of this variable to the global variable and you will be able to use it out side of the while loop */
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
// for each post a user has made, a new div will be echo's
echo "
<div class='message_wrapper'>
// all content here which displays the message and author.
// consider this anchor link, and see $_GET approach below.
<a href='/inc/del_post.php?id=$thought_id>'>Delete </a>
<div id='toggleComment$thought_id' class='new_comment'>
<form action='' method='post' enctype='multipart/form-data'>
<table>
<tr>
<td>
<textarea id='txtarea' name='comment_msg' cols='80' maxlength='180' placeholder=' add your comment...'></textarea>
</td>
<td>
<input id='send' type='submit' name='send_comm' value='Share'/>
</td>
</tr>
</table>
</form>
</div>
</div>";
} // while loop closed
// sending comments to database
$comment = htmlentities(trim(strip_tags(#$_POST['comment_msg'])));
$comment = mysqli_real_escape_string($connect, $comment);
// if button is pressed, do this...
if(isset($_POST['send_comm'])){
if (!empty ($comment)){
$insert_comment = mysqli_query ($connect, "INSERT INTO user_comments VALUES ('','$comment','$username','$user','0','$thought_id')");
header ("Location: /profile_page/$user");
}
}
?>

how to delete the specified row from html table and also in mysql table using php

I am currently displaying the data using a html table in php from mysql database, and i also i am allowing the user to delete only their own data from the table,my problem is how to match the delete button with the respected row,when user clicks the delete buttons only the specified row should be deleted, but it deletes all the records which is connected to the user in the database, please help me how to do this, PS i am a learner and new to php
UPDATED CODE GOES HERE
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>View cart-d2dn</title>
</head>
<body>
<?php
include('header.php'); ?>
<h1>View Cart</h1>
<table border='1'>
<tr>
<th> VIN </th>
<th> Vehicle Description </th>
<th> Price </th>
</tr>
<?php
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT vin,description,price FROM products where user_id='".$_SESSION['use_i']."' ";
$result = mysqli_query($conn, $sql);
$uq=mysql_query("select * from td_user where user_id='".$_SESSION['use_i']."' ");
$u_row=mysql_fetch_array($uq);
if(isset($_REQUEST['delete']))
{
$sql_s =" DELETE FROM `products` WHERE user_id='".$u_row['user_id']."' AND vin='".$_REQUEST['vin']."' " ;
$result_s = mysqli_query($conn,$sql_s) ;
if($result_s == true)
{
echo '<script language="javascript">';
echo 'alert("Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("Error in deletion")';
echo '</script>';
}
}
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr>
<td>'.$row['vin'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['price'].' </td>
<td> <form method="post"> <input type="submit" name="delete" value="Delete">
<input type="hidden" name="vin" value="'.$row['vin'].'">
</form></td>
</tr>';
}
}
else
{
echo "Your cart is empty!";
}
?>
<?php
echo '</table>';
?>
<form><input type="button" value="Go back" onClick="window.location.href='automobile_list.php'">
<input type="button" value="Submit" onClick="window.location.href='mail.php'">
</form>
<?php
mysqli_close($conn);
?>
<?php
include('footer.php');
?>
</body>
</html>
You can do same only if your MySQL table have primary/unique key OR each row is different...
If VIN is unique then Let me show where you need to change. You need to SEND the unique key with delete request to detect which row selected to be deleted. Change the delete button code to:
<form method="post"> <input type="submit" name="delete" value="Delete">
<input type="hidden" name="vin" value="'.$row['vin'].'">
</form>
And in code of deleting row:
if(isset($_REQUEST['delete']))
{
$sql_s =" DELETE FROM `products` WHERE user_id='".$_SESSION['use_i']."' AND vin='".$_REQUEST['vin']."' ";
}
ALSO Delete the mysql code you are using to retrieve user ID (which is just before the code written above). [AND put this delete-code before displaying table(before selecting from product table-look at comments for more info :p )]
If vin is not the primary key then add primary in table by following mathed:
In mysql workbench: right click -> Alter table -> add column ID as INT and check the PK (primary key), AI (auto increment) -> apply -> finish.
Now use ID in place of VIN
As you said you are new to PHP. Then let me give a suggestion:
Use $_POST in place of $_REQUEST coz POST var contains data which sent by POST method only BUT REQUEST contains both POST & GET data... so anybody can delete via just typing in URL as ?delete=delete&vin=3
BTW, its not the issue here, but will help you in future.
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr id="<?php echo $row['id']; ?>" >
<td>'.$row['vin'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['price'].' </td>
<td> <form method="post"> <input type="submit" name="delete" value="Delete"></form> </td>
</tr>';
$vinrow =$row['vin'] ;
}
}

How to delete user from MySQL database

I am a new PHP programmer. I created a user login page where can i see list of user who is logged in. I am using PDO for connecting database. The Problem is if I want to delete user from the list it only delete the last inserted user. What i am doing wrong ? Can someone please help me...
Here is my HTML code:
<form action="" method="post">
<?php
foreach($rows as $row){
$time = $row['time_out'];
echo "
<input type='text' value='$row[user_name]' name='user_name'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<input type='submit' value='submit' name='submit'>
<br>";
}
?>
</form>
if(isset($_POST['submit'])){
//get course
$course = $_POST['course'];
//get user_name
$user_name = $_POST['user_name'];
//deleting user from the database
$database->delete($user_name);
//Redirect to current page
header('Location: tutor.php');
exit;
}
Here is my method for getting logged in user:
public function selectFromOnline()
{
$sql = $this->connection()->prepare("SELECT * FROM online");
$sql->execute();
return $sql->fetchAll();
}
Here is my method for deleting user:
public function delete($user_name)
{
$sql = $this->connection()->prepare("DELETE FROM online WHERE user_name = :user_name");
$sql->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$sql->execute();
return $sql;
}
Sorry But I didn't understand your code but I understood your problem and here it is my solution with "mysqli_query"....
<?php
//Please set these veriables according to your values....
$host_name = "YOUR_DB_HOST_NAME"; //Normally 'localhost'
$password = "YOUR_PASSWORD_FOR_MYSQL"; //your password
$username = "YOUR_USERNAME_FOR_MYSQL"; //Normally Root
$database_name = "NAME_OF_YOUR_DATABASE";
$connect = mysqli_connect($host_name, $username, $password, $database_name);
if(!$connect){
echo "Something is Wrong Please Check your host name, user name, password or database name";
}
?>
<!--YOUR FORM STARTS----------------------------------------------------->
<!--DON'T FORGET TO SET ACTION TO #(ON THE SAME PAGE)------------------------------------>
<form action="#" method="post">
<?php
foreach($rows as $row){
$time = $row['time_out'];
//Any Two Input Fields Cant have same Name So...
echo "
<input type='text' value='$row[user_name]' name='user_name_display'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<input type='hidden' value='$row[user_name]' name='user_name'>
<input type='submit' value='submit' name='submit'>
<br>";
}
?>
</form>
<!--YOUR FORM ENDS----------------------------------------------------->
<?PHP
if(isset($_POST['submit'])){
//get course
$course = $_POST['course'];
//get user_name
$user_name = $_POST['user_name'];
//Creating and running mysqli query
$delete = "DELETE FROM online WHERE user_name='$user_name'";
$query = mysqli_query($connect, $delete);
if($query){
//Code to run when user is deleted
header("Location: tutor.php")
}else{
//Error to show when can't delete user
echo "Sorry Can't delete the user";
}
}
?>
Just forget about some semicolons and some minor errors (if there is any), It'll Defiantly Work....
Please Don't Forget to Vote if it works....
The problem is that every input has the same name so you get nothing when you try to obtain POST values. Try a different approach. Maybe you can add a new field (hyperlink) that performs the redirect action and send the parameters of deleting action with GET.
Example:
echo "
<input type='text' value='$row[user_name]' name='user_name'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<a href='Test.php?username=$row[user_name]&course=$row[course]'>delete</a>
<br>";
}
Test.php is the name of your php page.
Then you can query the database by using the the GET value:
$_GET["username"]

Categories