Why does this SQL execute but not update anything? - php

For some reason or another, this sql is executing and outputting:
successfully added the following paypal button to this product... But it's not updating. I'd appreciate any help on this.
if(isset($_REQUEST['submitedform'])) {
if ($_POST['paypal']) {
$paypal=$_POST['paypal'];
$id = $_GET['id'];
$query = "UPDATE `video_info` SET paypal_button_html='".$paypal
."' WHERE id='".mysql_real_escape_string($id) ."'";
mysql_query($query) or die(mysql_error());
echo "successfully added the following paypal button to this product:
<br /><br />
{$paypal}";
}
}
?>
<?
if ($_GET['id']) {
?>
<h1>Add PayPal Button In for this product:</h1>
<form action="add_paypal.php" method="POST">
*Paypal button html: <br><textarea rows="2" cols="20" name="paypal"></textarea><br>
<input type="hidden" name="submitedform" value="true" />
<input type="submit" value="Add paypal button in for this product">
</form>
<?
} else {
echo "You can not come to this page manually.";
}
?>

A few problems:
You were not being consistent in sanitising your Database Input
You did not have clear validation rules
Your form was not setting the $_GET['id'] field (so the database submission was always failing)
Amended code:
<?php
// Init an Array to hold any error messages
$errors = array();
if( isset( $_REQUEST['submitedform'] ) ){
// Validate the required fields
if( !isset( $_POST['paypal'] ) || $_POST['paypal']=='' )
$errors['paypal'] = 'No value for "paypal"';
if( !isset( $_GET['id'] ) || !is_numeric( $_GET['id'] ) )
$errors['id'] = 'No value for "id"';
// If Validation was successful
if( !$errors ){
// Prepare the Variables for Database Usage
$paypal = mysql_real_escape_string( $_POST['paypal'] );
$id = (int) $_GET['id'];
// Template and Complete the SQL Query
$sqlTpl = 'UPDATE `video_info` SET paypal_button_html="%s" WHERE `id` = %s';
$sqlStr = sprintf( $sqlTpl , $paypal , $id );
// Submit the Query
if( !mysql_query( $sqlStr ) ){
// Something went wrong
$errors[] = 'An error occured when submitting the data to the database';
}else{
// Submitted OK
echo 'Successfully added the following paypal button to this product:'.$paypal;
}
}
}
// Check for any errors
if( $errors ){
// Show errors to user
echo 'The following errors occurred:';
echo '<ul><li>'.implode( '</li><li>' , $errors ).'</li></ul>';
}
?>
<?
if( isset( $_GET['id'] ) && is_int( $_GET['id'] ) ){
?>
<h1>Add PayPal Button In for this product:</h1>
<form action="add_paypal.php?id=<?php echo $_GET['id']; ?>" method="POST">
*Paypal button html: <br><textarea rows="2" cols="20" name="paypal"></textarea><br>
<input type="hidden" name="submitedform" value="true" />
<input type="submit" value="Add paypal button in for this product">
</form>
<?
} else {
echo "You can not come to this page manually.";
}
?>
This code...
Includes the id in the form's action URL
Checks for the submission
Validates the submitted values
Creates the Database Query
Submits the Query
Checks the Query worked OK
AMENDED: Replaced is_int() with is_numeric() as, after RTFMing, I found that a string, comprised of only digits, will apparently return false if tested with is_int().

UPDATE
Please, use $_REQUEST OR $_GET OR $_POST but not all 3 of them.
Also, why don't you mysql_real_escape_string the variable $_POST['paypal'] ?

You mix $_GET and $_POST variables. You should use either GET or POST, but not both. If this is a post request, change $_GET['id'] to $_POST['id'].
In this case, the update doesn't fail because of where id = ''. This doesn't update anything, because there's no id with an empty string. But it also doesn't fail, since it is a valid update statement.

Related

$_POST setted after I unset it

Here, I have made validation for checkbox.
First when I select on submit button, it shows validation error.
After that when I click on "selectall" button, it goes in update query that is on submit button.
That mean, $_POST is setted.
I have unset that submit button for that, although it is going in update query through "selectall" button.
Why this is happening?
if(!empty($_SESSION['id']) && isset($_POST['processorder']))
{
echo "hello";exit;
$chk = $_SESSION['id'];
$query="update order_details set process_order='1' where id IN(".implode(',',$chk).")";
//mysql_query($query) or die(mysql_error());
unset($_SESSION['id']);
unset($_SESSION['on']);
$_SESSION['flash']['success'] = 'Order processed successfully.';
header('Location: '.$_SERVER['REQUEST_URI']);
die();
}
if(empty($_SESSION['id']) && $_POST['processorder'])
{
print_r($_POST);
$error = "Please select an Order(s)..!!";
unset($_POST['processorder']);
echo "<br>";
print_r($_POST);
}
<input type="button" name="selectpage" value="Select All Page" onclick="selectall()"/>
<input type="submit" id="processorder" name="processorder" value="Process Order" class="submit-green"/>
<input type="checkbox" name="id[]">
If you would like to unset all $_POST values you shouldn't just unset $_POST['processorder'].
if (isset($_SESSION['id']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
// to unset processorder
unset($_POST['processorder']);
var_dump($_POST);
// To unset all $_POST values
unset($_POST);
var_dump($_POST); // Will return bool(false)
}
Since you've unset($_SESSION['id']);, if(empty($_SESSION['id'])) will return TRUE.
This happens because if(empty(unset($var))) will always return TRUE.

I can't get my update query to work (php / mysqli)

I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>

PHP Form not directing to correct pages

I'm making a login page for the admins to make some changes to a website easily. However, the login page isn't working correctly. It won't go to the error page InvalidLogin.html and it won't go to the next page of the admin website AdminChanges.php.
Instead, I'm getting the following message:
Not Found
The requested URL /website/method="post" was not found on this server.
<?php
if ($_POST['submit'] == "submit")
{
$userName = $_POST['username'];
$passWord = $_POST['password'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$checkUserNameQuery = "SELECT username FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWordQuery = "SELECT password FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
$AdminChanges = "AdminChanges.php";
}
else
{
$AdminChanges = "InvalidLogin.html";
}
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action = <?php PrepSQL($AdminChanges); ?> method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Two problems are joining forces to cause this error. First, your PrepSQL function does not echo the response, and neither does the code that calls it. You need to echo or print the response so that it appears in your generated HTML.
<?php echo PrepSQL($AdminChanges); ?>
Second, you need to encapsulate that value of the action attribute in double-quotes, like this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
Also note that your code assumes that your mysql_query() statements were successful. For troubleshooting purposes, you should at least add an or die(mysql_error()) statement to the end of the mysql_query() lines. This will allow your code to provide some feedback when the query fails.
Additionally, please note that your query-handling method will never result in a valid login response.
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
mysql_query() returns a MySQL resource, not a single field from the database. Your code attempts to compare that resource to the supplied username and password, and the comparison will always fail. For details about handling the results of mysql_query() see the documentation.
Replace:
PrepSQL($AdminChanges);
with:
print PrepSQL($AdminChanges);
Try this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
You need to echo the value.
There are 2 errors I noticed:
Your $_POST['submit'] if statement doesn't let $AdminChanges be set for the form unless it has already been submitted.
To fix this you could change your if submit statement to just redirect to your invalid login page like so:
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
//Correct info do what you need to here
}
else
{
header("Location: InvalidLogin.html");
exit();
}
And also:
You need to change the action to go post to this page.
<form action="<? $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">

Add to total of field from Database in PHP

I have a script that I'm using that when the user enters a code I want it to add to the total in the database, however nothing is happening.
This is my code so far:
$err = array();
if (isset($_POST['doSubmit4']) === true ) // Was if ($_POST['access']=='submit')
{
$code = mysql_real_escape_string($_POST['access-key']); // Was $data['access-key']
$result = mysql_query("SELECT `akid`,`key`,`total_access` FROM access_keys WHERE id='$_SESSION[user_id]' AND type='1'") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the key exists.
if ( $num > 0 ) {
list($akid,$key,$total_access) = mysql_fetch_row($result);
if ($code == $key) {
if(empty($err)){
$total_access++;
mysql_query("update access_keys set total_access='$total_access' where akid='$akid'") or die(mysql_error());
header("Location: ./");
}
} else {
$err[] = "Invalid Access Key. Please try again with correct access key.";
}
} else {
$err[] = "Error - Invalid Access Key. No access exists for your user ID.";
}
}
I'm wanting it to add to the Total Access field each time the user enters the correct code, but it's not working.
This is my form code:
<form name="postAccess" id="postAccess" method="post" action="access.php">
<input type="password" name="access-key" id="access-key" style="background-color:black;color:white;" size="40" /><br/>
<input name="doSubmit4" type="submit" id="doSubmit4" value="submit">
</form>
It might be your parent if brackets.
Try:
if (isset($_POST['access']) === true )
instead of
if ( $_POST['access']=='submit' )
If that doesn't seem to do it, do some debugging.
Throw some echo statements in those if brackets to see what conditions are true and what are not.
EDIT:
I just realized another problem.
Your form action is invalid. This should be the path to the page you are posting the data to. So:
Instead of:
<form name="access" id="access" method="post" action="access">
You should have:
<form name="access" id="access" method="post" action="your-php-path-here.php">
Notice how action = "your-php-path-here.php" in the above code.

php $_POST var clearing itself when i check it

i have a crazy problem that i just can't figure out. my form has two fields and a submit button. when i submit the vars get passed into $_POST just fine...
print('<div class=error>');
print_r($_POST);
print('</div>');
that gives me the two fields with the expected values along with the value of the submit button.
HOWEVER! when i add the following line of code so i can process based on the submit button, it clears all of the data. the post array shows up empty.
if ($_POST['submit'] == 'Submit') {
that clears the data. if i change the value from 'Submit' to anything else, the vars still show up in $_POST, they just get cleared when i try to check them.
any ideas what i'm doing wrong here?
here's the form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<?
if (isset($msg)) {
echo "$msg";
}
?>
<input type=text name='email'><br>
<br><input type=password name='password'>
<br>
<input type="submit" name="submit" value=Submit>
</form>
and here's the processing code:
if ($_POST['submit'] == 'Submit') {
echo "<div class=error>made it here</div>";
$u = $_POST['email'];
$p = $_POST['password'];
$auth = mysql_query("Select * from member where email='$u' and password='$p'");
$auth = mysql_fetch_array($auth);
if ($auth) {
$pid = $auth[id];
echo "aa";
sess_register("sess_msg");
$sess_msg = null;
global $auth, $pid;
}
}
if i change the value when i check to see if the submit button has a value to something other than the actual value of the submit button, which is 'Submit' - it clears all variables sent to $_POST
If you want to check which submit button was clicked, you just have to look for its name as a key in the array $_POST.
So you should do:
if (array_key_exists('submit', $_POST)) {
// your code
}
Little advice: you'd better escape your $_POST data before putting it into a query!
Check this out: http://php.net/manual/en/function.mysql-real-escape-string.php
From your post, it doesn't look your code should be emptying the $_POST array. The only thing that I can think of at the moment is that maybe in the code you actually only put one '=' sign.
var_dump( $_POST );
if ( isset( $_POST['submit'] ) ) {
var_dump( $_POST );
echo "<div class=error>made it here</div>";
$u = $_POST['email'];
$p = $_POST['password'];
$auth = mysql_query("Select * from member where email='$u' and password='$p'");
$auth = mysql_fetch_array($auth);
if ($auth) {
$pid = $auth[id];
echo "aa";
sess_register("sess_msg");
$sess_msg = null;
global $auth, $pid;
}
}
var_dump( $_POST );

Categories