I am using the following script to process a form that updates a message on my website, the problem I am having is that it is clearing the row instead of updating it for some reason. I have copied the query from Phpmyadmin so I know its correct, and I have also tried echoing the posted values and they all echo out just fine too, but for some unknown reason when I click submit in the form it just wipes the contents of the record instead of updating it.
<?php
include("connectmysqli.php");
if (isset($_POST['OnOff'])) {$OnOff = $_POST['OnOff'];}else {$OnOff = '';}
if (isset($_POST['title'])) {$title = $_POST['title'];}else {$title = '';}
if (isset($_POST['message'])) {$message = $_POST['message'];}else {$message = '';}
$stmt = $db->prepare("UPDATE `itsnb_chronoforms_data_urgentform` SET `title` = '$title',`message` = '$message',`OnOff` = '$OnOff' WHERE `cf_id` =1;");
if (!$stmt) trigger_error($db->error);
$stmt->execute();
echo 'Message Updated !';
echo '<p>Back To Main Menu</p>';
?>
This is the table :
did you echo the generated query?
there are exactly to ways I see this can happen:
your form input names do not match the post keys you check in the three if statements
you're not sending the form with method="post"
also you should only execute the update query if all three post fields are set and valid. like title and message must not be blank/empty and that onOff variable should eighter contain "on" or "off". otherwise echo an errormessage so the user knows what's wrong with his input.
Related
I am trying to delete a row using a href, it's not showing the error but it's not delete the row from my table either. Not sure what i'm doing wrong.
delete.php
require_once "db.php";
$id = $_GET['id'];
$sql = "DELETE FROM books WHERE isbn = ". $id;
if (mysqli_query($db, $sql)){
echo "Success";
}else{
echo "Error";
}
main.php
if($resultSet->num_rows > 0){
while($rows = $resultSet->fetch_assoc()){
$au = $rows['author'];
$bt = $rows['booktitle'];
$rev = $rows['reserved'];
echo"<tr><td>$au</td><td>$bt</td><td>$rev</td><td><a href='delete.php?id=".$rows['isbn']."'>Delete</a></td></tr>\n";
}
echo"</table>";
}
I used a back quote (`) around the field name and it is OK now.
Example:
DELETE FROM table WHERE `field_name` = something
It seems like if you're getting the success message then the query ran successfully, which means that the database connection established OK so we can rule that out.
I think that your query is running but not finding any match on the ISBN so the record isn't getting deleted. I would try echoing out the actual SQL query just before execution so you can then copy it, connect to the database and then paste that query in to run yourself. Maybe change it to a SELECT statement first so you can see if it actually gets the row for deletion. If not then a row with that ISBN either doesn't exist or you've got something strange like an extraneous space/other weird character in the ID somewhere.
I have this code and it seems to be working. The values are updating, but when I reload the page the updated values are without any value. For example now I have set the title as "blablabla" and when I reload the page it's changing to "".
This is the code
<?php
$title = $_POST['title'];
$meta = $_POST['meta'];
$email = $_POST['email'];
$analytics = $_POST['analytics'];
$query = "UPDATE websettings SET title = '$title', meta = '$meta', email = '$email', analytics = '$analytics' WHERE id = '1'";
if(mysql_query($query)){
echo "success";
}
else {
echo "fail";
}
?>
Your code applies $_POST variables to the database, but doesn't check if the client actually posted anything. Better to check if $_POST contains array items (if a form was posted), and check if each of those is set (if the user filled in the right fields), and validate the user input before saving (phone numbers, emails etc formatted correctly).
And as was pointed out in the comments you are vulnerable to SQL injection attack - one of the first things you should address.
Try turning on more PHP errors too - these would flag as unset variables for quicker fixing.
I am implementing a minutes form, where minutes of a meeting between a student and supervisor are saved within a database table called 'minute.php'. When a student is adding minutes, they are required to enter some data but some fields need to be disabled for only a supervisor to enter.
However when i disable the text box it throws an error that the field cannot be null as the database is expecting something...
Also, i have pre-filled two of the fields (Bnumber and Status), however when the 'add minutes' form appears these fields are not pre-populated, any one have any idea how to go about this?
<?php
include ("dbConnect.php");
include ("studenthead.php");
session_start();
if (!(isset($_SESSION["sess_username"]))) header ("Location: index.php");
$currentUser=$_SESSION["sess_username"];
if (isset($_POST['addMinute'])) {
$newB_number = $currentUser;
$newDate = $_POST['Date'];
$newTime = $_POST['Time'];
$newDiscussion = $_POST['Discussion'];
$newActions = $_POST['Actions'];
$newDateofnextmeeting = $_POST['Dateofnextmeeting'];
$newStatus = "Submitted";
$newSupervisor_comments = $_POST['Supervisor_comments'];
$dbQuery = $db->prepare("insert into minute values (null, :newB_number, :newDate, :newTime, :newDiscussion, :newActions, :newDateofnextmeeting, :newStatus, :newSupervisor_comments )");
$dbParams = array('$newB_number'=>$newB_number, 'newDate'=>$newDate, 'newTime'=>$newTime, 'newDiscussion'=>$newDiscussion, 'newActions'=>$newActions, 'newDateofnextmeeting'=>$newDateofnextmeeting, 'newStatus'=>$newStatus, 'newSupervisor_comments'=>$newSupervisor_comments);
$dbQuery->execute($dbParams);
$lastInserted = $db->lastInsertId();
}
?>
You would either need to change your DB schema to allow for null values, or you need to send an empty string.
You are not showing you code that generates the form, but pre-populateing a value is as simple as:
<input type="text" name="B_number" value="<?php echo $b_number; ?" />
This is of course assuming you have already determined the value you want to pre-populate into the filed and stored in $b_number variable.
I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.