I am trying to figure out why this mysql update query doesn't actually update the mysql database!
I cannot find the reason why!
The page gets an ID from add.php file and the values related to that ID get echo-ed in the form properly but for some reason it doesn't update the mysql at all!!
could someone please let me know if I am missing something?
here is my code:
<?php
// Script Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['title'])) {
$pid = mysqli_real_escape_string($db_conx, $_POST['thisID']);
$title = mysqli_real_escape_string($db_conx, $_POST['title']);
$details = mysqli_real_escape_string($db_conx, $_POST['details']);
// See if that product name is an identical match to another product in the system
$sql = "UPDATE pages SET title='$title', details='$details', WHERE id='$pid'";
$query = mysqli_query($db_conx, $sql);
header("location: add.php");
exit();
}
?>
<?php
// Gather this product's full information for inserting automatically into the edit form below on page
if (isset($_GET['pid'])) {
$targetID = $_GET['pid'];
$sql = "SELECT * FROM pages WHERE id='$targetID' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$title = $row["title"];
$details = $row["details"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "Sorry, that don't exist.";
exit();
}
}
?>
and here is the HTML form in the page:
<form action="pages_edit.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Page Tile</td>
<td width="80%"><label>
<input name="title" type="text" id="title" size="64" value="<?php echo $title; ?>" />
</label></td>
</tr>
<tr>
<td align="right">Page Body</td>
<td><label>
<textarea name="details" id="details" cols="64" rows="5"><?php echo $details; ?></textarea>
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input name="thisID" type="text" value="<?php echo $targetID; ?>" />
<input type="submit" name="button" id="button" value="Make Changes" />
</label></td>
</tr>
</table>
</form>
You're probably getting errors from the database server and ignoring them. Use mysqli_error() to inspect the errors.
For starters, you have an extra comma in your query. You don't need a comma before the WHERE clause, so change to:
UPDATE pages SET title='$title', details='$details' WHERE id='$pid'
Additionally, is the id column really a string? It's more likely that it's an integer. (Unless, of course, you made it a string. Check the table schema to know for certain.) If that's the case then you wouldn't want to surround the value with single-quotes. So change to:
UPDATE pages SET title='$title', details='$details' WHERE id=$pid
There could very well be other errors. Check the database response (as mentioned before) for errors, and check the PHP logs for errors. You need to debug your code, don't just look at it and guess what the problems might be.
Furthermore, it's worth noting that your code is currently highly vulnerable to SQL injection attacks. Luckily, the PHP documentation explains the concept thoroughly, and has examples of alternatives.
Related
I have the following code to display and modify a simple sqlite table
<?php
$db = new SQLite3("my_sqlite.db");
$query = "SELECT rowid, * FROM students";
$result = $db->query($query);
if( isset($_POST['submit_data']) ){
// Gets the data from post
$name = $_POST['name'];
$email = $_POST['email'];
$query = "UPDATE students set name='$name', email='$email'";
if( $db->exec($query) ){
echo "Data is updated successfully.";
}else{
echo "Sorry, Data is not updated.";
}
}
?>
<table border="1">
<form action="" method="post">
<tr>
<td>Name</td>
<td>Email</td>
</tr>
<?php while($row = $result->fetchArray()) {?>
<tr>
<td><input name="name" type="text" value="<?php echo $row['name'];?>"></td>
<td><input name="email" type="text" value="<?php echo $row['email'];?>"></td>
</tr>
<?php } ?>
<input name="submit_data" type="submit" value="Update Data">
</form>
</table>
PROBLEM: When I change some of the information and update, the whole column changes into the same change. E.g.: if I write a the name Nick, every name changes into Nick.
First, you should only do updates for one record at a time so each record needs its own update button. Attached is the corresponding rơwid of the record. you can use:
<input type="hidden" name="rowid" value="$row['rowid]">
You should add a WHERE clause to the update statement to know exactly which records should be updated.If you omit the WHERE clause, ALL records will be updated!
I have a super easy question. I have a form that echoes out a mySQL record that the user can update. I make my changes, and it tells me that the update is successful, but when I look at the table, the changes do not go through. What is the problem here?
This is the first script.
<?php
require_once("models/config.php");
?>
<table border=1>
<tr>
<td align=center>Edit Form</td>
</tr>
<tr>
<td>
<table>
<?
$personid=$_SERVER['QUERY_STRING'];
$order = "SELECT * FROM persons where personid='$personid'";
$result = mysqli_query($mysqli,$order);
$row = mysqli_fetch_array($result);
?>
<form method="post" action="edit_data.php">
<input type="hidden" name="id" value="<? echo "$row[personid]"?>">
<tr>Person ID:<? echo "$row[personid]"?></tr>
<tr>
<td>First Name</td>
<td>
<input type="text" name="firstname"
size="20" value="<? echo "$row[firstname]"?>">
</td>
</tr>
<tr>
<td>Surname</td>
<td>
<input type="text" name="surname" size="40"
value="<? echo "$row[surname]"?>">
</td>
</tr>
<tr>
<td align="right">
<input type="submit"
name="submit value" value="Edit">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
Which then goes through to this:
<?
require_once("models/config.php");
$personid = $_POST['personid'];
$firstname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['firstname']));
$surname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['surname']));
$order = "UPDATE persons SET firstname='$firstname', surname='$surname' WHERE personid='$personid'";
$result = mysqli_query($mysqli,$order);
if (!$result) {
echo "Error entering data! <BR>";
echo mysql_error();
} else {
echo "User updated to $firstname $surname <BR>";
}
?>
Is there something I am missing here?
Thanks in advance.
You are sending a hidden input named id and trying to use a $_POST['personid']
correct that
You may also pay attention to the comments you had (SQL Injection's one at least)
Your form sends the id in the field id, while you refer to it as personid.
The reason why this appears to be working, is that the update in itself is correct. $personid is treated as an empty string, so the update correctly updates all records that have an empty personid, which is no record at all.
OK, so here is a revised script with prepared statements. The script is working in the sense that updates are being made to the records. Two questions:
1) is this safe from My-SQL injections?
2) This is updating records successfully, but now it is echoing out "Error entering data!", how come?
<?
require_once("models/config.php");
$personid = $_POST['personid'];
$firstname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['firstname']));
$surname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['surname']));
$order = "UPDATE persons SET firstname=?, surname=? WHERE personid=?";
$stmt = mysqli_prepare($mysqli, $order);
mysqli_stmt_bind_param($stmt, "ssi", $_POST['firstname'], $_POST['surname'], $_POST['personid']);
mysqli_stmt_execute($stmt);
$result = mysqli_query($mysqli,$stmt);
if (!$result) {
echo "Error entering data! <BR>";
echo mysqli_error($mysqli);
} else {
echo "User updated to $firstname $surname <BR>";
}
?>
I'm sure the second question is a rather boneheaded one - do I just reverse the conditions?
I made this code:
<?php if($this->session->userdata('login_user_id'));
$a = $this->session->userdata('login_user_id');
$b = mysql_query("SELECT * FROM user WHERE id='$a' AND specialrank='1'")
or die(mysql_error());
while($c = mysql_fetch_array( $b ))
{
Print $c['username'];
}
?>
basically it creates a session for the logged in user.
I want to be able to show more in the print section though, some advanced php code and html form. Is there a way I can do this by reworking the code? It seems I'm limited with regards to which characters I can use within the print statement.
Basically, I want to display a form to specific users and not others.
I have tried closing the <?php ?> tags after every line to see if that works but it throws up errors of unexpected and expected's etc.
EDIT:
this is the segment of code I want to show:
<?php // update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE pins SET is_private = $emp_salary WHERE id = $pinDetails->id";
mysql_select_db('test_db');$retval = mysql_query( $sql );if(! $retval )
{ die('Could not change: ' . mysql_error());
}
echo "Post is now private<br><br>";
}
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Private
<input name="emp_salary" type="text" id="emp_salary" value="1">
<input name="id" type="hidden" id="id">
<input name="update" type="submit" id="update" value="Change">
</td>
</tr>
</table>
</form>
As you can see, simply putting that within the print throws up so many errors.
I have been working on a project and i am at the final stages of the project. My problem is whenever i try to update data in my database table into returns a blank screen with no error messages. Please find the php script and html form (the form responsible for updating the database table) below, i have divided it into about four sections:
Thanks in advance
Update Form:
<a name="inventoryEditForm" id="inventoryEditForm"></a>
<h3>↓Add New Question Form↓</h3>
<form action="inventory_edit.php" enctype="multipart/from-data" name="myForm" id="myForm" method="post">
<table width="80%" border="0" cellspacing="3" cellpadding="7">
<tr>
<td width="20%"> </td>
<td width="80%"> </td>
</tr>
<tr>
<td>Question</td>
<td><textarea rows="" name="question" cols=""><?php echo $question; ?></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Venue</td>
<td><input type="text" name="venue" maxlength="50" value="<?php echo $venue; ?>"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="questiondate" value="<?php echo $date; ?>"></td>
</tr>
</table>
<br>
<input name="thisID" type="hidden" value="<?php echo $targetID; ?>"/>
<input type="submit" name="submit" value="Update Question">
<input type="reset" name="clear" value="Clear Form">
</form>
PHP Script:
<?php
//Error reporting due to long script
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
error_reporting(E_PARSE);
//Update question table
If (isset($_POST['question'])) {
$id = mysqli_real_escape_string($link, $_POST['thisID']);
$question = mysqli_real_escape_string($link, $_POST['question']);
$venue = mysqli_real_escape_string($link, $_POST['venue']);
$date = mysqli_real_escape_string($link, $_POST['questiondate']);
//Update question in the table
$sql = mysqli_query($link, "UPDATE DebateQuestion SET question='$question',venue='$venue',date='$date' WHERE qQuestionNo='$id'LIMIT 1") or die(mysql_error());
header("location: inventory.php");
exit();
}
?>
<?php
error_reporting(E_PARSE);
//Gather this questions full information and insert automatically into the edit form
if (isset($_GET['qid'])) {
$targetID = $_GET['qid'];
$sql = mysqli_query($link, "SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1") or die(mysql_error());
$questionCount = mysqli_num_rows($sql); // count the output amount
if ($questionCount > 0) {
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
$id = $row["qQuestionNo"];
$question = $row["qQuestion"];
$venue = $row["qDebateVenue"];
$date = strftime("%b %d, %Y", strtotime($row["qDate"]));
}
} else {
echo "Oops, no questions like that exists. Check <a href='inventory.php'>inventory</a>again";
exit();
}
}
?>
In your update query you have the data column without using ` back ticks , date is also a mysql's function try to wrap up your column names with back ticks if you are not sure whether they conflict with mysql's reserved keywords
$sql = mysqli_query($link,"UPDATE DebateQuestion SET
`question`='$question',`venue`='$venue',`date`='$date'
WHERE qQuestionNo='$id'LIMIT 1")
"SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1"
Here is qQuestionNo column a string type?if not remove quotes around $targetID.
Note : I have not tested the code - just read it on screen.
I've never seen an IF statement capitalized before :
If (isset($_POST['question'])) {
I'd guess this makes a difference however.
There's lots of other weird things going on in your files, but none that should give you white screen. Try lowercase 'I' in your if statement first.
ALSO - re: the UPDATE statement, you are missing a space between the $id and the LIMIT :
**qQuestionNo='$id'LIMIT 1**
I have a form whereby users are required to anwser their own security question before proceeding further. my form is as follows:
<form action="securitychecked.php" method="post">
<table width="70%" border="0">
<tr>
<td><?php $result = mysql_query("SELECT secret_question FROM public WHERE active = 'activated' AND ni = '". $_SESSION['ni']."'")
or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo '<hr><h4>This Person Has Not Setup A Security Question</h4><hr> ';
} else {
while($info = mysql_fetch_array($result))
{
echo $info['secret_question'];
}
}?></td>
<td><span id="sprytextfield1">
<input type="text" name="secret_answer" id="secret_answer" />
<span class="textfieldRequiredMsg">*</span></span></td>
</tr>
<tr>
<td> </td>
<td><br /><input name="" type="submit" value="Continue" /></td>
</tr>
</table>
</form>
my php code looks like this:
<?php
$secret_anwser=$_POST['secret_anwser'];
$secret_anwser = stripslashes($secret_anwser);
$secret_anwser = mysql_real_escape_string($secret_anwser);
$sql="SELECT secret_anwser FROM public WHERE secret_anwser ='$secret_anwser' AND active = 'activated' AND ni = '". $_SESSION['ni']."'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
header("location:votenow.php");
}
?>
I have a table called public and a field called 'secret_anwser' but i keep on getting a blank page even with the right value being entered. can anyone help me?
thanks
I guess all the secret_anwser in your PHP are typo's.
At least the fields name is secret_answer but you try to get $_POST['secret_anwser']; , you'll never find anything inside the DB.
The names of the DB and the table also may be wrong.