I am trying to update a record in a database. The code is meant to allow users to update an entry on a website with the option to edit the image as well. When I was initially testing this code it worked with no issues. When they selected an image it would update the image, and when they did not select an image it would not include the image in the updating. When I moved this code to the page that it needs to be on it is no longer working. It is always reading it as if the user has not selected an image to upload. The only thing that has changed between the test code and this code is the names in the database, and the addition of mysql_real_escape_string() for the variables $title and $description.
Here is the PHP code that is not working for me:
<?php
require_once ("connect.php");
if (isset($_POST['description'])) {
$id = $_GET['id'];
$title = $_POST['title'];
$description = $_POST['description'];
$title = mysql_real_escape_string($title);
$description = mysql_real_escape_string($description);
$target = "../images/contests/";
$target = $target.basename( $_FILES['image']['name']);
$ok=1;
if($_FILES['image']['name'] == "") {
$query = "UPDATE tbl_contests SET contests_title='$title', contests_description='$description' WHERE contests_id='$id'";
$result = mysql_query ($query);
if ($result) {
header ("Location: contests.php?=noimage");
exit ();
} else {
header ("Location: contests.php?=error");
exit ();
}
} else {
if ($ok==0){
header("Location: contests.php?=error");
} else {
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
echo "<p>Your upload was sucessful.</p>";
$query = "UPDATE tbl_contests SET contests_title='$title', contests_description='$description', contests_image='$target' WHERE contests_id='$id'";
$result = mysql_query ($query);
if ($result) {
header ("Location: contests.php?=image");
exit ();
} else {
header ("Location: contests.php?=error");
exit ();
}
}
}
}
}
?>
Here is the form pertaining to the above code:
<?php
$postnum = $_GET['id'];
$query = "SELECT * FROM tbl_contests WHERE contests_id=".$postnum;
$result= mysql_query($query);
$row = mysql_fetch_array($result);
$path = "../images/contests/";
?>
<form action="update-past.php?id=<?php print $row[contests_id]; ?>" method="post" id="updatepast">
<br /><label>Title:</label> <p><input type="text" name="title" id="title" class="input" value="<?php print $row[contests_title]; ?>" /></p>
<?php if ($row['contests_image'] == !null) { ?>
<p><img src="<?php print $path.$row['contests_image']; ?>" width="425" height="500" /></p>
<br /><label>Edit Image: (Optional)</label> <p><input name="image" type="file" id="image" class="file" size="50" /></p>
<?php } else { ?>
<br /><br /><br /><br /><label>Add Image: (Optional)</label> <p><input name="image" type="file" id="image" class="file" size="50" /></p>
<?php } ?>
<br /><br /><br /><br /><br /><label>Description:</label><p><textarea name="description" cols="85" id="description" class="contentinput" rows="10"><?php print $row[contests_description]; ?></textarea></p>
<p><input type="submit" name="submit" id="button" value="Edit" /></p>
</form>
Try adding this to the form: enctype="multipart/form-data"
Here's some reading on form content types: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
Related
I am a newbie to PHP. & My PHP Code doesn't work, I want to update some date using MySQL but it seems that first IF condition is 'false' i don't why, I am using PHP 7 & XAMP as a local host, Dreamweaver as an IDE & this is my code:
if(isset($_POST["btn_edit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
if(!empty($_FILES["img"]["name"]))
{
$img = $_FILES["img"]["name"];
$img_temp = $_FILES["img"]["tmp_name"];
if(move_uploaded_file($img_temp, "assets/images/".$img))
{
$query = mysqli_query($Connection, "UPDATE entry_data SET names='$name',emails='$name',passwords='$password',images='$img' WHERE id='$ID'");
if($query)
{
$result = header("Location:index.php");
}
else
{
echo mysql_error();
}
}
}
else
{
$query = mysqli_query($Connection, "UPDATE entry_data SET names='$name',emails='$name',passwords='$password',images='$img' WHERE id='$ID'");
if($query)
{
echo "<h5>Updated</h5>";
}
}
}
it showing me nothing just refresh the page & this is HTML CODE:
<form method="post" enctype="multipart/form-data">
<input name="name" value="<?php echo $name ?>" />
<input name="email" value="<?php echo $email ?>" />
<input name="password" value="<?php echo $password ?>" />
<img width="50" height="50" src="<?php echo 'assets/images/'.$row[4] ?>" />
<input name="img" type="file" class="text-info" required="required" />
<br/>
<input name"btn_edit" type="submit" />
<?php if(isset($_POST["btn_edit"])) echo $result ?>
You have syntax issue in your button HTML.
This:-
<input name"btn_edit" type="submit" />
Need to be:-
<input name="btn_edit" type="submit" /><!-- = is missing in name -->
I'm trying to create a landing page and there should be one download button. So when the button was clicked and the form has been completed correctly the user will be redirected to the thank you page but when the form has not been completed correctly I will redirect the user to an error page. How can I realize this?
My code for the form:
<form method="post" action="index.php">
<input type="email" name="iptEmail" placeholder="MaxMustermann#gmail.com" required />
<br /><br />
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
<img src="img/reloadCaptcha.png" alt="reloadCaptcha.png">
<br /><br />
<input type="text" name="captcha_code" id="iptCaptcha" placeholder="Code" size="10" minlength="6" maxlength="6" required />
<br /><br />
<button name="btnSubmit">DOWNLOAD</button>
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if(array_key_exists('btnSubmit',$_POST)){
if ($securimage->check($_POST['captcha_code']) == false) {
$_SESSION['status'] = "error";
} else {
if(isset($_POST['btnSubmit'])){
$mailKunde = $_POST['iptEmail'];
$betreff = "";
$message = "";
$absName = "";
$absMail = "";
$replyTo = "";
$anhang = "./data/test.zip";
mail_att($mailKunde, $betreff, $message, $absName, $absMail, $replyTo, $anhang);
$_SESSION['status'] = "thanks";
}
}
}
?>
</form>
My code for the body:
<body>
<?php
if ($_SESSION['status'] == "home") {
include('php/home.php');
} elseif ($_SESSION['status'] == "error") {
include('php/error.php');
} elseif ($_SESSION['status'] == "thanks") {
include('php/thanks.php');
}
?>
</body>
Consider the following,
you may redirect the user to a different page using this line of code:
<?php
if(some_condition...){
header("Location: someotherplace.php");
}
also, if you have already sent html output before this line, you can simply emit a javascript redirect:
<?php
if(some_condition...){
echo("<script>;location.href='someotherplace.php';</script>");
}
I'm working in a update file using php and mysql but the update function doesn't work. I wrote the code using an example and modified according to the requirements. The file does work and doesn't really drop any error but it doesn't change anything in the database. It is suppose to update a book database.
Code:
<?php
$page_title = 'Add Books';
include ('bookincludes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize an error array.
if (empty($_POST['title'])) {
$errors[] = 'Please add title.';
} else {
$e = mysqli_real_escape_string($dbc, trim($_POST['title']));
}
if (empty($_POST['author'])) {
$errors[] = 'Please add the name of the author.';
} else {
$p = mysqli_real_escape_string($dbc, trim($_POST['author']));
}
if (!empty($_POST['isbn1'])) {
if ($_POST['isbn1'] != $_POST['isbn2']) {
$errors[] = 'ISBN number does not match.';
} else {
$np = mysqli_real_escape_string($dbc, trim($_POST['isbn1']));
}
} else {
$errors[] = 'You need to enter ISBN number.';
}
if (empty($errors)) { // If everything's OK.
$q = "SELECT ISBN FROM Books WHERE (Title='$e' AND Author ='$p')";
$r = #mysqli_query($dbc, $q);
$num = #mysqli_num_rows($r);
if ($num == 1) { // Match was made.
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Make the UPDATE query:
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = $row[0] ";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message.
echo '<h1>Thank you!</h1>
<p>Thank you, Book has been added or modified</p><p><br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">System error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
mysqli_close($dbc); // Close the database connection.
// Include the footer and quit the script (to not show the form).
include ('includes/footer.html');
exit();
} else {
echo '<h1>Error!</h1>
<p class="error">ISBN number is incorrect.</p>';
}
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
<h1>Update</h1>
<form action="Bupdate.php" method="post">
<p>ISBN number: <input type="text" name="isbn1" size="20" maxlength="60" value="<?php if (isset($_POST['isbn1'])) echo $_POST['isbn1']; ?>" /> </p>
<p>Confirm ISBN: <input type="text" name="isbn2" size="20" maxlength="60" value="<?php if (isset($_POST['isbn2'])) echo $_POST['isbn2']; ?>" /> </p>
<p>Author: <input type="text" name="author" size="20" maxlength="60" value="<?php if (isset($_POST['author'])) echo $_POST['author']; ?>" /></p>
<p>Title: <input type="text"" name="title" size="20" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; ?>" /></p>
<p>Year: <input type="text"" name="year" size="20" maxlength="60" value="<?php if (isset($_POST['year'])) echo $_POST['year']; ?>" /></p>
<p><input type="submit" name="submit" value="Update" /></p>
</form>
<?php include ('bookincludes/footer.html'); ?>
This is what If I try to change the ISBN got:
System error. We apologize for any inconvenience.
Query: UPDATE Books SET ISBN='978-1782175910' WHERE ISBN =
978-1782175919
If I tried to update the ISBN or the year but I get the message above.
How can I fix this?
The query requires that text values are wrapped in quotes like this
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = '$row[0]'";
Although I would look for a tutorial that uses parameterised and prepared queries rather than string concatenated queries to avoid SQL Injection
And any tutorial that suggests using the # error silencing prefix should tell you the author has no idea what they are doing and should be avoided like the plague.
you seem to be missing single quotes on your where clause
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = 978-1782175919
should be
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = '978-1782175919'
i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.
I have a working php guestbook script. It's only 1 file. I tried to validate it and there is only one error:
Line 147, Column 36: required attribute "action" not specified
<form method="post" name="blogform">
Now the code is this and I'm sure I would need to break up the file to two so that I can create a file for the action tag but I just don't know how. Any help is much appreciated.
<?php
session_start();
include("../../4a/inc/opendb.inc.php");
if(isset($_POST['send'])) //checks if $_POST variable "is set"
if(isset($_SESSION["ellenorzo"]) && !empty($_SESSION["ellenorzo"]) && $_SESSION["ellenorzo"]==$_POST["code"]){
$name = trim($_POST['name']); //eliminating whitespaces
$email = trim($_POST['email']);
$message = addslashes( trim($_POST['message']));
$query = "INSERT INTO blog (name, email, message, date) " .
"VALUES ('$name', '$email', '$message', NOW())";
mysql_query($query) or die('Hey, something is wrong!' . mysql_error());
header('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
?>
<?php
include('../../4a/inc/head.inc.php');
?>
<body style="color: #ffffff;">
<div class="mainblog">
<div class="top">
<div class="menu">
<?php
include('../menu.inc.php');
?>
</div>
</div>
<div class="middleblog">
<form method="post" name="blogform">
<input name="name" id="name" class="nameblog" type="text" />
<img src="../../4a/img/main/name.jpg" class="name" alt="Name" />
<input name="email" id="email" class="emailblog" type="text" />
<img src="../../4a/img/main/email.jpg" class="email" alt="Email" />
<textarea name="message" id="message" class="messageblog" rows="6" cols="6" onkeyup="return ismaxlength(this)">
</textarea>
<img src="../../4a/img/main/message.jpg" class="message" alt="Message" />
<input name="send" value="submit" id="send" class="sendblog" type="image" src="../../4a/img/main/send.jpg" onclick="return checkform();" />
<input type="hidden" name="send" value="submit" />
<div class="text_check_code">
<font class="text">
Enter the characters as they are shown below.
</font>
</div>
<img src="../../4a/inc/secure.inc.php" class="img_check_code" alt="Nospam" />
<input name="code" class="input_check_code" />
</form>
<?php
$rowsperpage = 10;
$pagenumber = 1;
if(isset($_GET['page']))
{
$pagenumber = $_GET['page'];
}
$offset = ($pagenumber - 1) * $rowsperpage;
$query = "SELECT id, name, email, message, date ".
"FROM blog ".
"ORDER BY id DESC ".
"LIMIT $offset, $rowsperpage";
$result = mysql_query($query) or die('Hey, something is wrong!. ' . mysql_error());
if(mysql_num_rows($result) == 0)
{
print("<br /><br /><br /><br /><br /><br /><br /><br />The blog is empty.");
}
else
{
while($row = mysql_fetch_array($result))
{
list($id, $name, $email, $message, $date) = $row;
$name = htmlspecialchars($name);
$email = htmlspecialchars($email);
$message = htmlspecialchars($message);
$message = stripslashes(nl2br($message)); //real breaks as user hits enter
?>
<br />
<div class="blogentries">
<b><?=$name?></b>
<br />
<?=$message?>
<br />
<i><?=$date?></i>
</div>
<br />
<?php
} //closing while statement
$query = "SELECT COUNT(id) AS numrows FROM blog";
$result = mysql_query($query) or die('Hey, something is wrong!. ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxpage = ceil($numrows/$rowsperpage); //rounding up any integer eg. 4,1=5
$nextlink = '';
if($maxpage > 1)
{
$self = $_SERVER['PHP_SELF'];
$nextlink = array();
for($page = 1; $page <= $maxpage; $page++)
{
$nextlink[] = "$page";
}
$nextlink = "Next: " . implode(' » ', $nextlink); //returns all elements of an array as a string
}
include ("../../4a/inc/closedb.inc.php");
?>
<br />
<div class="nextlink">
<?=$nextlink;?>
</div>
</div>
<br />
<br />
<div class="bottomblog">
<?php
require_once('../../4a/inc/copyright.inc.php');
?>
</div>
<br />
<br />
</div>
<?php //closing the else statement
}
?>
<?php
include('../../4a/inc/footer.inc.php');
?>
The action property specifies the link the form is sent to. If the form calls itself you can leave it blank:
<form action="" method="post" name="blogform">
The action tag tells the form where to submit the data. If it is left blank, it will attempt to submit the data to the current php page. If it's giving you trouble, perhaps you need to specify it and point it to the php page that generates the form.
In the code you provided, the bit of code which handles new inserts is at the top of this page, so you should set the action tag to be the name of the page.
By the way, you should ensure that your inputs are all cleaned; just using trim() before inserting them is asking for trouble. See here for more on this topic.