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);
}
?>
Related
Trying to make a CRUD, everything works except my Update function. I feel like the problem is in the second sql query. When I click on submit it just refreshes and the change is gone. Can anyone show me how to find what I need to change/show me what to change?
<head>
<title>Update</title>
</head>
<body>
</form>
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<form action="" method="post">';
echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
echo "<br>";
echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
echo "<br>";
echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>";
echo "<br>";
echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
echo "</form>";
}
echo "</table>";
} else {
echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
?>
Instead of building a form inside PHP, just break with ending PHP tag inside your while loop and write your HTML in a clean way then start PHP again. So you don't make any mistake.
Also you've to submit your $id from your form too.
Try this
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $id ?>" />
Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
<br>
Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
<br>
City: <input type="text" name="City" value="<?= $row['City'] ?>" />
<br>
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</form>
<?php
} // end while loop
echo "</table>";
}
else {
echo "0 results";
}
Note: You are passing undefined variables into your update query. As you are submitting your form you must have to define those variables before you use them.
if (isset($_POST['Submit'])) {
$CName = $_POST['CName'];
$Contact = $_POST['Contact'];
$City = $_POST['City'];
$id = $_POST['id'];
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
that loop? ID primary key or not?
maybe u need create more key in table dealer like as_id
<input type="hidden" name="idform" value="$as_id">
in statment
if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}
So I'm just making a simple program that puts names into a database. I got that part down, I can enter a name into a form, then display it on the page, but now I'd like to know how to delete them from the database, and no longer show them on the page.
I added a button next to each name that triggers the third if statement (with the commented out query), and from what I can tell it's best to run a query based on the element's id (my primary key that auto increments), but I have no idea how to get the id from the element who's button I'm clicking on.
How do I get the id from one of the elements in my while loop? Or if there's a better way to delete them, what's that?
if (mysqli_connect_errno()) {
die('could not connect');
}
if (isset($_POST['first_name'], $_POST['last_name'])){
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$putitin = mysqli_query($db, "INSERT INTO names (first_name, last_name) VALUES ('$first_name', '$last_name')");
}
if (isset($_POST['del'])){
//$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = ");
}
?>
<html>
<head>
</head>
<body>
<form action='' method='post'>
<div>
<label for "first_name">First name</label>
<input type="text" name="first_name">
</div>
<div>
<label for "last_name">Last name</label>
<input type="text" name="last_name">
</div>
<div>
<input type="submit" value="Insert">
</div>
</form>
<hr>
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo "<form action='' method='post'><p>Name: $fname $lname $id<input type='submit' name='del'></form></p>";
}
} else {
echo 'No results';
}
?>
</body>
</html>
This is one way.
change your html part to
<form action='' method='post'>
<input type='hidden' name='id' value='$id' />
<p>Name: $fname $lname $id
<input type='submit' name='del' value=''>
</form></p>
and your php
if (isset($_POST['del'])){
$id = $_POST['id'];
$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = '$id'");
}
Note:
What you can do is to put all your input fields inside your while loop. Then assign values to each of them, but we have to use array to store them accordingly.
We can use checkbox to store the IDs.
What will happen, is user can select from the list of names they wanted to delete by ticking the corresponding checkbox, then pressing the Delete button below.
Your code
<form action="" method="POST">
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo '<input type="checkbox" name="id[]" value="'.$id.'">'.$fname.' '.$lname.'<br>';
} /* END OF WHILE LOOP */
?>
<input type="submit" value="Delete" name="delete">
</form>
And your PHP that will process the form:
<?php
if(isset($_POST["delete"])){
$counter = count($_POST["id"]);
for($x = 0; $x<$counter; $x++){
if(!empty($_POST["id"][$x])){ /* CHECK IF AN ITEM IS SELECTED */
/* DELETE QUERY */
if($stmt = $db->prepare("DELETE FROM names WHERE id = ?")){
$stmt->bind_param("i",$_POST["id"][$x]);
$stmt->execute();
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF IF; CHECKING IF IT IS SELECTED */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
?>
I'm trying to create a form that allows a user to select a field from a drop down box and then change what is currently written in the field.
My current code allows me to view the drop down list select the field I want to change and then enter my new text into a box. But when I click update, nothing happens.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT * FROM news_updates";
$result=mysql_query($query) or die("Query Failed : ".mysql_error());
$i=0;
while($rows=mysql_fetch_array($result))
{
$roll[$i]=$rows['Text'];
$i++;
}
$total_elmt=count($roll);
?>
---------------------------------------------------------Now I have the form
<form method="POST" action="">
Select the news post to Update: <select name="sel">
<option>Select</option>
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
?>
</select><br />
Text Field: <input name="username" type="text" /><br />
<input name="submit" type="submit" value="Update"/><br />
<input name="reset" type="reset" value="Reset"/>
</form>
-----------------------------------------------Now I have the update php
<?php
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Well, you seem to be missing the $value part. Something like this should do, for the last part:
<?php
if(isset($_POST['submit']))
{
$username = mysql_real_escape_string($_POST['username']);
$value = mysql_real_escape_string($_POST['sel']);
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
echo $query2; //For test, to see what is generated, and sent to database
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Also, you should not use mysql_* functions as they are deprecated. You should switch to mysqli or PDO.
First, try adding a value to your options, like so:
for($j=0;$j<$total_elmt;$j++)
{
?>
<option value="<?php echo $roll['id']; ?>"><?php echo $roll['option_name']; ?></option>
<?php
}
Then, when you parse your file, go like so:
$value = $_POST['sel']; // add any desired security here
That should do it for you
You need to change this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
to this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option value="<?php echo $roll[$j];?>"> <?php echo $roll[$j];?></option> <?php
}
And you also need to change the update query from this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
to this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='".$_POST['sel']."'";
N. B.: Here I am assuming that $_POST['sel'] has the value selected by the user from the drop down menu because I could not find anything which corresponds to $value
I am trying to edit data in my database but i cant get it to work.
i have tried breaking the script down to basics and troubleshoot each part.
The delete button works just fine but editting the data doesn't.
Where have i gone wrong?
my structure
database = domains table = domains_info row = domain
<?php include("header.php");
//include database connection
include 'db_connect.php';
$action = isset( $_POST['action'] ) ? $_POST['action'] : "";
if($action == "update"){
//write query
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."',
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
if( $mysqli->query($query) ) {
echo "User was updated.";
}else{
echo "Database Error: Unable to update record.";
}
}
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM domains_info WHERE id='".$mysqli->real_escape_string($_GET['id'])."'";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}}
$query = "select id, domain
from domains_info
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'
limit 0,1";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$id = $row['id'];
$domain = $row['domain'];?>
<form action='#' method='post' border='0' class="well form-horizontal">
<fieldset>
<label class="control-label" for="name">Domain</label>
<div class="controls">
<input id="name" type="text" name="name" value="<?php echo$domain; ?>">
<input type='hidden' name='id' value='<?php echo $id ?>' />
<!-- we will set the action to edit -->
<input type='hidden' name='action' value='update' />
<input type='submit' value='Edit' />
</fieldset>
</form>
<?php echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>"; ?>
<script type='text/javascript'>
function delete_user( id ){
//prompt the user
var answer = confirm('Are you sure you want to delete <?php echo$name; ?>?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id of the record to be deleted
window.location = 'deletecontact.php?id=' + id;
}
}
</script>
the error im getting is this
Database Error: Unable to update record.
There is a extra ',' in your update query
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."',
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
with
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."'
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
I do have programming experience, but new to php. I do have an issue with an example I was doing from this tutorial. I looked over it millions of times, googled, ect ect. I don't have an idea why my code isnt working.
The purpose is to basically just test inserting and deleting in sql from php, using a button for Add Record and Delete Record. The Add record button works perfectly, but delete doesnt do a thing other than reload the page. Heres the code...
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['type']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
if (isset($_POST['delete']) && $isbn != "")
{
echo "worked!!!!!!!!!!!!!!";
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
//if (!mysql_query($query, $db_server))
//echo "DELETE failed: $query" . mysql_error();
}
else
{
echo "nooooooooooooooooooo";
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$type', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Type $row[2]
Year $row[3]
ISBN $row[4]
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="$row[4]" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
I have looked over this many times, still no idea why this won't work. Is it the for loop that is making this button not work? Note, you will see echo "worked!!!"; and in the else echo "noooooooo"; that was for me to test whether the button was being tested, yet nothing prints. So maybe i missed something in the button code itself? Also, no errors are printed, and my editor (and myself) have missed the syntax error (if thats the case).
The code for the delete button is at the end, before I closed the DB.
Thanks for your help in advance.
Your problem is your first if block.
You're checking for the presence of the posted variables author title type year isbn. Whereas in your delete code the only variables sent are delete and isbn. Therefore the first if block is completely missed (including the delete code).
You need to modify your first if to be if(isset($_POST)) { // a form has been posted. Then it should work.
Another way to do it:
if(isset($_POST['delete']) && isset($_POST['isbn']) && !empty($_POST['isbn'])){
//delete code here
}
if(isset($_POST['author']) && isset($_POST['title']) && isset....){
// insert code here
}
EDIT: rewritten code:
<?php // sqltest.php
// I don't know what's in here, so I've left it
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST))
{
if (isset($_POST['delete']) && !empty($_POST['isbn']))
{
echo "Deleting";
$query = "DELETE FROM classics WHERE isbn='".mysql_real_escape_string($_POST['isbn'])."'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
}
else
{
echo "Inserting";
$query = "INSERT INTO classics VALUES ('".mysql_real_escape_string($_POST['author'])."', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['type'])."', '".mysql_real_escape_string($_POST['year'])."', '".mysql_real_escape_string($_POST['isbn'])."')";
if (!mysql_query($query))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
// you don't need echo's here... just html
?>
<form action="sqltest.php" method="post">
<pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre>
</form>
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
// a better way to do this:
while($row = mysql_fetch_array($result)){
?>
<pre>
Author <?php echo $row[0]; ?>
Title <?php echo $row[1]; ?>
Type <?php echo $row[2]; ?>
Year <?php echo $row[3]; ?>
ISBN <?php echo $row[4]; ?>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="<?php echo $row[4]; ?>" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
<?php
}
mysql_close($db_server);
?>
Verify the method you used in your form. Make sure it's POST like this:
Form action="yourpage.php" method="POST"
and in your code above, replace the following:
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
with
$author = $_POST['author'];
$title = $_POST['title'];
$type = $_POST['type'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
Finally, there is no need to check again if the $isbn is not null as you did it in your isset() method. So remove $isbn!="" in the if below:
if (isset($_POST['delete']) && $isbn != "")
{
}
becomes:
if (isset($_POST['delete']))
{
}
Since you are testing, checking if the user clicked the delete button is of less importance. So you can also remove it for a while and add it later because you are sure that, that code is accessible after clicking the delete button.
You have no form field named delete, so it is impossible for your delete code path to ever be taken.
I'm guessing you're tryign to use the value of the submit button to decide what to do? In that case, you're also missing a name attribute on the submit button - without that, it cannot submit any value with the form. You probably want:
<input type="submit" name="submit" value="DELETE RECORD" />
and then have
if (isset($_POST['submit']) && ($_POST['submit'] == 'DELETE RECORD')) {
...
}