php and mysql code - php

I have checked and rechecked my code for a tutorial that I am doing, and I still cannot figure out what is wrong with it. A bit of help would be appreciated.
I am building a page that processes the form data from another page. The part of the markup that I am having trouble with is below.
<pre>
if (isset($_POST['submit'])) {
// Process the form
$subject_id = $_GET["subject"];
$pageName = $_POST["pageName"];
$pagePosition = $_POST["pagePosition"];
$pageVisible = $_POST["pageVisible"];
$pageContent = $_POST["pageContent"];
if (!empty($errors)) {
$_SESSION["errors"] = $errors;
redirect_to("new_page.php");
}
$query = "INSERT INTO pages ( subject_id, menu_name, position, visible, content ) VALUES ('{$subject_id}' , {$pageName}, {$pagePosition} ,{$pageVisible} ,{$pageContent} )";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Page created.";
redirect_to("manage_content.php");
} else {
// Failure
$_SESSION["message"] = "Page creation failed.";
redirect_to("new_page.php?subject={$subject_id}");
}
</pre>
I have checked out the page that submits to the form processing page and the form submits correctly. I've also checked all the external functions that I reference and all of them work. Additionaly, the first variable that uses the $_GET superglobal works just fine. The problem is in the query somehow not being able to pull in the 4 $_POST variables. If I substitute all the variable values with hard-code values, the query goes through fine and creates a new row in my table.
Any help with this would be appreciated, as I have checked and rechecked this so many times, and I am sure I'm missing something very small, but it's driving me crazy.
Thanks.

You're missing quotes around your string values:
$query = "INSERT INTO pages ( subject_id, menu_name, position, visible, content ) VALUES ('{$subject_id}' , '{$pageName}', {$pagePosition} ,{$pageVisible} ,'{$pageContent}' )";
This would have been obvious if you checked for errors using mysqli_error().

Related

$_POST is removing a single quote (OR how to get a single quote into a $_POST) [duplicate]

This question already has answers here:
Escape double quotes with variable inside HTML echo [duplicate]
(3 answers)
Closed 1 year ago.
First want to start off by saying that I am still a beginner developer but have gotten a long way in a short time and I am somewhat stumped. And yes I know my code might not be pretty in layout, but still learning, at least things are working.
I am creating something that is like a client portal for shows. A client signs up to do a show from an intake form. When they submit the form, it goes to Monday.com, creates a folder and sub folder in dropbox and then inserts everything into my Mysql database. I also then have another page (Assets) where they can upload files based on the show. Now if they have signed up for multiple shows, at the top of this page I have a dropdown box that grabs all the shows that is assigned to their used id. When they click on the show that they want to add files to and then click the "Choose Show For Asset Upload" button it goes back to the database to retrieve the dropbox path and the file request url and puts it into the code where those variables are assigned. So, everything is working great except when it comes to a show that has a single quote (apostrophe). I noticed this when I added a test show and everything went bonkers. I was able to figure everything out when it comes to making it correct in the code for Monday and Dropbox and even INSERTing it into the database. In the database column it has "Michael's" instead of "Michael\'s", so it's exactly how it should be in there. In the dropdown it actually shows "Michael's" but yet when I do an echo after clicking the button it shows "Michael" So that single quote is definitely the issue and this is where I don't know how to fix it, after much searching through the net.
In the dropdown it lists (Show Test, Did I Really Do It!!, Dudley, The Amazing MA, Lets See If This Works, Michael's).
Code is:
<div class="topdiv">
<h2 style="text-align: center;">Assets Upload</h2><br>
</div>
<?php
$userid = $_SESSION["userid"];
$sql = "SELECT * FROM intake WHERE userid = ?;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $userid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
?>
<form class="formcenter" action="assets.php" method="post">
<select name="show" id="show">
<?php
while ($rows = mysqli_fetch_assoc($result)) {
$show = $rows['showtitle'];
echo "<option value='$show'>$show</option>";
}
?>
</select>
<input type="submit" name="chooseShow" value="Choose Show For Asset Upload"><br><br>
</form>
<?php
if(isset($_POST["chooseShow"])) {
$showTitle = $_POST["show"]; //WHEN I DO AN ECHO OF THIS IT SHOWS "MICHAEL" NOT "MICHAEL'S"
$sql = "SELECT * FROM intake WHERE userid = ? and showtitle = ? ;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $userid, $showTitle);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rows = mysqli_fetch_assoc($result);
$path = $rows['dbxPath'];
$requestURL = $rows['requestURL'];
echo $show; //THERE JUST TO SEE WHAT IT WAS OUTPUTTING
echo $showTitle; //THERE JUST TO SEE WHAT WAS OUTPUTTING
}
}
?>
When I do the two echos at the end of the code $show = "Michael's" and $showTitle = "Michael". So I do know that the correct way is coming through but just can't grab it to put in the last $sql variable to use as the $showTitle Granted, I am assuming the $show is showing "Michael's" because it's the last show in the loop. BUT when I tested $show instead of $showTitle in the mysqli_stmt_bind_param statement it actually worked, so I know it's possible. Just need to know how to get the full "Michael's" into my $showTitle variable.
Thank you for taking the time to look through this longwinded (trying to give you as much info as possible) question and appreciate any help and advice.
-Michael
Your problem is here:
echo "<option value='$show'>$show</option>";
The single quotes in the variable $show are interfering with the single quotes wrapping the value.
Change it to this:
echo '<option value="'.$show.'">'.$show."</option>";
This explicitly concatenates the parts of the string rather than interpolating it. It gives better control over what quotes are used and where.

Updating database info from php, not saving

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.

Editing a form with PHP and MySQL: Best way to obtain an ID

I have a MYSQL table with edit and delete links on each row. The edit link goes to edit_patient.php which has a form (actually, a copy of the form originally used to insert patient into the database). After few tries, the script is working although I guess it could be improved (indeed, I get a notice of "Undefined index: id" when I submit the edits. The ID is passed to the edit_patient.php file through a GET procedure. Relevant code as follows:
// Check for a valid user ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_patient.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p>Sorry, it is not possible to update patient info at this time</p>';
include ('../elements/layouts/footer.php');
exit();
}
And, after some clean up and check on submitted values:
if($action['result'] != 'error'){
// Make the query:
$q = "UPDATE `demographics`
SET lastname='$lastname', firstname='$firstname', clinic='$clinic', sex='$sex', dob='$dob', age='$age',
disease_1='$disease_1', disease_2='$disease_2', disease_3='$disease_3', address='$address', city='$city', country='$country',
zip='$zip', phone_1='$phone_1', phone_2='$phone_2', phone_3='$phone_3', email_1='$email_1', email_2='$email_2',
physician='$physician', notes='$notes'
WHERE dem_id=$id
LIMIT 1";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_affected_rows($db_connect) == 1) { // If it ran OK.
// Tell the user we have edited patient data successfully
$action['result'] = 'success';
array_push($text,'Patient data have been updated on databank');
}else{
$action['result'] = 'error';
array_push($text,'Patient data could not be changed on databank. Reason: ' .
'<p>' . mysqli_error($db_connect) . '<br /><br />Query: ' . $r . '</p>');
} // End of if (empty($errors)) IF.
} // End of if (empty rows))
Ok, so far so good. Now, in order to show already inserted data, I run another query:
// Retrieve the user's information:
$q = "SELECT lastname, firstname, clinic, sex, dob, age, disease_1, disease_2, disease_3, address, city, country, zip, phone_1,
phone_2, phone_3, email_1, email_2, physician, notes
FROM `demographics`
WHERE dem_id='".$_GET['id']."'";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.
// Get the user's information:
$row = mysqli_fetch_assoc ($r);
// Create the form:
Here, the critical row I do not understand is WHERE dem_id='".$_GET['id']."'"; --> If I it leave as it is, the script runs almost Ok but then I get a notice of undefined index id.
However, when I replace with WHERE dem_id=$id"; as in the first query, the script gives a fatal error of undefined variable: id.
Finally, to submit the form I use the following command:
" /> that is working Ok, but it is not working when I use:
" />
Can anyone help me to understand why, and how to correct the issue, I'd rather prefer to be able to use simply $id (I believe is straight forward and simple) but for some reason is not working as expected. Finally, I would like to be able to report in the form to be edited also data inserted with radio buttons and drop-down (select) menus. Any advice on that would be greatly appreciated !
Please make sure that your specific record has been updated after the submit button in your edit_patient.php ? If it works and after next which page is display ..? Is it is Display.php (i.e. all record display page ) ? Please be specify first and i really help you to solve your query.

PHP to Update MySQL Database Table

First off, just wanted to say I'm a novice at this type of coding, although I'm hopeful that I'll eventually make sense of it all with a little guidance.
I have a MySQL database table (promotion) that stores a bunch of redemption codes for various products (for a give away contest). The idea is, the first person to enter the redemption code wins the product, and their info should be stored in the "promotion" table.
The table's columns are: redeem_id (Auto Increment field), redeem_code, redeemer_email, redeemer_first_name, redeemer_last_name, and redeem_date_time.
Initially, the redeem_id and redeem_code fields are the only ones with any data. What I'd like to happen is when a user enters their information (name, email, etc) and submit a redemption code, their info will populate the rest of the row for that particular code. If anyone else tries to submit a code that has already been redeemed, they should receive an error message - likewise for an invalid code (i.e. a code that does not exist in the table).
The PHP code I have so far is:
<?php
function get_promotion_by_redeem_code($redeem_code)
{
$sql = "SELECT * FROM promotion WHERE redeem_code= '".mysql_real_escape_string($redeem_code)."'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row;
}
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).", redeemer_first_name=".mysql_real_escape_string($first_name).", redeemer_last_name=".mysql_real_escape_string($last_name).", redeem_date_time=NOW(), WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
$insert = mysql_query($query);
return $insert;
}
$email=$_POST['e_mail'];
$first_name=$_POST['f_name'];
$last_name=$_POST['l_name'];
$redeem_code=$_POST['v_code'];
$connection = mysql_connect('localhost', 'db', 'pw');
mysql_select_db('db', $connection);
$promotion = get_promotion_by_redeem_code($redeem_code);
if ($promotion) {
if (!$promotion['redeemer_email']) {
redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code);
echo 'Congratulations, you have successfully claimed this item!';
} else {
echo 'Sorry, this item has already been redeemed.';
}
} else {
echo 'Sorry, you have entered an incorrect claim code. Please use your browser\'s back button to try again.';
}
mysql_close($connection);
?>
It works as expected when I enter an invalid claim code, or if a code's row has been previously populated.
When it doesn't work, is when someone goes to redeem the item for the first time. Essentially, it will show the "Congratulations" message, however the table doesn't get updated for the submitted information. Therefore, no matter how many times the correct code is entered, the user will receive the "Congratulations" message.
I'm fairly certain that the error is in the redeem_promotion() function, but I can't figure out where.
You have add an extra comma(,) before WHERE clause. Thats the mistake, i think.
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).",
redeemer_first_name=".mysql_real_escape_string($first_name).",
redeemer_last_name=".mysql_real_escape_string($last_name).",
redeem_date_time=NOW()
WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
**OR**
$query = "UPDATE promotion
SET redeemer_email='".mysql_real_escape_string($email)."',
redeemer_first_name='".mysql_real_escape_string($first_name)."',
redeemer_last_name='".mysql_real_escape_string($last_name)."',
redeem_date_time=NOW()
WHERE redeem_code='".mysql_real_escape_string($redeem_code)."'";
$insert = mysql_query($query);
return $insert;
}

Can you use $_POST in a WHERE clause

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.

Categories