Form values populated with old variable - php

I am trying to create a page where users can edit information.
I can can populate the form with values from an array and update them, however, when it is saved and visited again with different array info it displays the previous form data. I have looked at clearing the cache and setting the array to NULL after the page has been submitted but neither of these have worked!
Here is what i have:
$id = ($_GET['id']);
function get_edit_event_details() {
global $connection;
$query = 'SELECT *
FROM events
WHERE id = "$id"';
$event_details = mysql_query($query, $connection);
confirm_query($event_details);
return $event_details;
echo $query;
}
$event_details = get_event_details();
$details = mysql_fetch_array($event_details);
and to populate the form values (I have also tried autocomplete="off" which has not worked either)
<input type="text" name="event_date" id="event_date" size="27" value="<?php echo $details["date"];?>" autocomplete="off" />
I am relatively new to PHP and have been able to solve every problem I have come across apart from this one!

I know that maybe this is not a real answer, but I'd like to point out some things:
Your ID should be casted to INT, as now you're vulnerable to injections.
So, it should be $id = intval($_GET['id']);
How is your ID passing to the function? it's outside, and not passed as a parameter, nor made global. I believe this could be the issue, as your query will always be without and ID to use as a condition. Try with:
get_edit_event_details($id){}
Personal taste maybe, but using 2 functions and and external call to the return value, just to fetch results it's a bit smelly. I'd rewrite the whole thing as:
function get_edit_event_details($_GET['id'])
{
global $connection;
$id = intval($_GET['id']);
$query = "SELECT * FROM events WHERE id = '$id'";
$result = mysql_query($query, $connection) or trigger_error('Query error: '.mysql_error());
if(mysql_num_rows($result) > 0)
{
return mysql_fetch_array($result);
}
else
{
return FALSE;
}
}
if($details = get_edit_event_details($_GET['id']) :?>
<input type="text" name="event_date" id="event_date" size="27" value="<?php echo $details["date"];?>" autocomplete="off" />
<?php endif;?>
Keep in mind that this is still not perfect code, I know, kinda smell mine too :). You might want to check if $_GET['id'] is set also, inside or outside the function.

Related

Accessing a sql database with two different functions

I'm making a movie rating website for a project and how to do the rating system has left me at a blank. Please let me know of a proper way to this if you know.
This gets the movie number from the url and displays the relevant information in the page
<body>
<?php
global $conn;
$conn = mysqli_connect('localhost','root','','filmsdb');
function show()
{
global $film;
global $conn;
$film = $_GET['fm'];
$sql = "SELECT * FROM movies WHERE m_No='$film'";
$ok = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($ok);
$c_r= $data[8];
$c_rc= $data[9];
?>
//displays the movie information and uses radio buttons to get user rating
Then this lets the user rate the movie
<?php
}
function act1()
{
if(isset($_POST['rsub']))
{
global $film;
global $conn;
$rate = $_POST['rate'];
$sqlr= "UPDATE movies SET rating=rating+$rate, rate_count=rate_count+1 WHERE m_No='$film'";
$output = mysqli_query($conn,$sqlr);
}
if($output==1)
{
echo 'Data Stored';
}
else
{
echo 'Data Not Stored ';
echo mysqli_error($conn);
}
}
$conn = null;
?>
</body>
</html>
when only the first function is being used, it works, but when I try to use the rating system, this error comes in the browser, mysqli_query() expects parameter 1 to be mysqli, null given... Any idea on a workaround for this?
Your issue is that the two variables you're relying on with the DB connection, $conn and $film, do not exist when the page has posted back the user rating data.
Your application's lifecycle goes like this:
1) User makes initial request. PHP starts and runs the first code block, it echoes some values to the page, page is returned to the user. Once the page is returned, the request is complete and PHP stops executing. All variables declared and in memory are lost because the process has stopped running.
2) The page returned from the PHP script arrives in the user's browser. User enters their rating and posts the data back to the server. This constitutes an entirely new request.
3) The new request arrives at the server. PHP starts up again. The web is inherently stateless, so by default it remembers nothing of the previous request. Certainly not the names or values in any in-memory variables - the process that contained them died long ago and has no association with the new one.
Therefore, if you have any values that you need to use again in PHP for the second request, you can either create them again, or receive them in the request data, or the first PHP script must have stored them somewhere persistent that you can retrieve them from, such as a session variable or cookie, or database.
It's not clear from your posted code, but presumably in the second request the function act1() gets called somehow and tries to insert the data into the database. It fails because neither $film or $conn have any values in them in this new request.
I suggest you solve it like this:
1) Create your connection object again, this is easy, and you need to re-connect to MySQL for this request anyway.
2) the film you're rating should be passed back from the browser in the form data.
This is the first script, to get the initial film data and render the ratings form to the page.
//re-usable function to connect to DB. Maybe move this out to a separate file so all pages can use it.
function getDBConn() {
return mysqli_connect('localhost','root','','filmsdb');
}
function show()
{
$conn = getDBConn();
$film = $_GET['fm'];
$sql = "SELECT * FROM movies WHERE m_No='$film'";
$ok = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($ok);
$c_r= $data[8];
$c_rc= $data[9];
$conn = null;
}
Your latest update doesn't show the form but I'm going to assume it's something like this, with an additional film hidden field. There should be suitable form tags around it as well.
<input type="radio" value="1" name="rate">
<input type="radio" value="2" name="rate">
<input type="radio" value="3" name="rate">
<input type="radio" value="4" name="rate"><input type="radio" value="5" name="rate">
<input type="hidden" name="film" value="<?php echo $film;?>"/>
<input type="submit" value="Rate" name="rsub">
Now is the second script, to be run when the rating data is submitted. You haven't shown how act1() is called but I'll assume you've got that covered.
function act1()
{
if(isset($_POST['rsub']))
{
$film = $_POST['film']; //get the film ID from the submitted form
$conn = getDBConn(); //assuming this script is in the same .php file as the first block, otherwise you'll need to move getDBConn into a separate php file and then include the file in each script.
$rate = $_POST['rate'];
$sqlr = "UPDATE movies SET rating=rating+$rate, rate_count=rate_count+1 WHERE m_No='$film'";
$output = mysqli_query($conn, $sqlr);
}
if ($output==1)
{
echo 'Data Stored';
}
else
{
echo 'Data Not Stored';
echo mysqli_error($conn);
}
$conn = null;
}
P.S. I know it's just an example project, but if you make a real-life site please heed the comments above re SQL injection, and don't let your applications and websites log into your DB as "root" either - give them only the privileges they actually need.

Query result into variable

I'm making a website. I want it so that I can put records into the database via my website. So first I need to select the id from which record I want to change. Then I want to put the values of the selected id into a variable. The I want to put the variable into a form value.
I'm trying to make something similar to phpmyadmin. If you click on the pencil you go to a form were everything is complete and you can just change the things you want to change and save it into the database.
wijzigen.php:
<form id="form1" name="form1" method="post" action="set_wijziging.php">
<h1>Selecteer het vuurwerkid van het product dat u wilt wijzigen</h1>
<p>Vuurwerkid <br>
<input type="text" name="vuurwerkid" id="vuurwerkid" />
<input type="submit" name="wijzigen" id="wijzigen" value="wijzigen"/>
</form>
and here is the part were I put what I typed in in the form into a variable.
<?php
$vuurwerkid=$_POST["vuurwerkid"];
?>
Then I'm trying to make a query wich only selects the things were vuurwerkid='$vuurwerkid'
So here I try to put the results of the query into a variable. But this doesn't seem to work.
set_wijziging.php:
<?php
include("connect.php");
$vuurwerkid=$_POST["vuurwerkid"];
$query = "SELECT * FROM vuurwerk_info WERE vuurwerkid='$vuurwerkid'";
$resultaat = MySQL_query($query);
while ($row = MySQL_fetch_array($resultaat))
{
$vuurwerkid="$row["vuurwerkid"]";
$naam=$row["naam"];
$prijs=$row["prijs"];
$soort=$row["soort"];
$cat_vuurwerk=$row["cat_vuurwerk"];
$aantal=$row["aantal"];
}
?>
I'm just started learning PHP
Your where spelling is wrong in your query
Try this
$query = "SELECT * FROM vuurwerk_info WHERE vuurwerkid='$vuurwerkid'";
I miss that last time Change this line as well
$vuurwerkid="$row["vuurwerkid"]";
To this
`$vuurwerkid=$row["vuurwerkid"];
//Remove the Double queite. As its variable not string`
although function name are case-incensitive. But change theese lines as well
chnage this
$resultaat = MySQL_query($query);
while ($row = MySQL_fetch_array($resultaat))
To this
$resultaat = mysql_query($query);
while ($row = mysql_fetch_array($resultaat))
Note I change nothing in the below line. I just used the small letter to right those function
Please learn MYSQLI_ OR PDO
As mysql function are depriciated.
You should change your $query to
$query = "SELECT * FROM vuurwerk_info WHERE vuurwerkid='$vuurwerkid'";
Also try to echo your query to see if it's correct.
Finally as others pointed out you should stop using mysql_* and switch to msqli or PDO.

Error trying to UPDATE php/mysql code for changing to a new password

As described in the title, I am running into an SQL injection error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
How do I fix this? Provided below is my php code and html code
PHP:
if($_POST['submit']=='Change')
{
$err = array();
if(!$_POST['password1'] || !$_POST['passwordnew1'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['password1'] = mysql_real_escape_string($_POST['password1']);
$_POST['passwordnew1'] = mysql_real_escape_string($_POST['passwordnew1']);
$row = mysql_fetch_assoc(mysql_query("SELECT id,username FROM members WHERE username='{$_SESSION['username']}' AND pass='".md5($_POST['password1'])."'"));
if($row['username'])
{
$querynewpass = mysql_query("UPDATE members SET pass='".md5($_POST['passwordnew1'])."' WHERE username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
else $err[]='Wrong Password To Start With!';
}
if($err)
$_SESSION['msg']['passwordchange-err'] = implode('<br />',$err);
header("Location: members.php?id=" . $_SESSION['username']);
exit;
}
HTML:
<form action="" method="post">
<?php
if($_SESSION['msg']['passwordchange-err'])
{
echo '<div class="err">'.$_SESSION['msg']['passwordchange-err'].'</div>';
unset($_SESSION['msg']['passwordchange-err']);
}
if($_SESSION['msg']['passwordchange-success'])
{
echo '<div class="success">'.$_SESSION['msg']['passwordchange-success'].'</div>';
unset($_SESSION['msg']['passwordchange-success']);
}
?>
<label class="grey" for="password1">Current Password:</label>
<input class="field" type="password" name="password1" id="password1" value="" size="23" />
<label class="grey" for="password">New Password:</label>
<input class="field" type="password" name="passwordnew1" id="passwordnew1" size="23" />
<input type="submit" name="submit" value="Change" class="bt_register" style="margin-left: 382px;" />
</form>
I have it working where a user is able to change/update their password, however, when they click the Change button on the form, they are directed to that error message I posted above, and if they click the refresh button, only then they are redirected back to their profile and the changes have been made. So my main question at hand is, how do I get this to fully work without that mysql error message? Any help would be much appreciated!
A few things wrong here, more than can be put in a comment. I'm sorry, I can't see exactly what your error is, but if you follow point #1, it'll go away.
Don't use the mysql library. It is deprecated, and has been removed (finally!) in PHP 5.5. It is only working for you at the moment, because your version of PHP is out of date. You should either be using PDO or MySQLi. Check out this article for information on PDO: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
Don't put any variable that's not generated in the script you're looking at into your query, this includes SESSION variables. You just need one flaw in your application, and the user can inject data into the SESSION. Treat every variable as dirty. If you know that it isn't - 100% for certain - then treat it as dirty. If you use prepared statements with PDO or MySQLi, this isn't a problem.
You should reference users by their ID, not username. Much faster and safer.
Never ever ever ever store passwords raw or simply encrypted (like with plain md5()) in the database. At the very least, you can encrypt with something like: crypt($password, '$2a$07$sillystring' . sha1($password) . '$') and verify by recrpyting the password and see if it matches. That's a very basic, more secure way of doing it. There are many articles written on password salting that go more in depth and are worth checking out.
Except for what Connor said, you have a serious problem here:
if($row['username'])
{
$querynewpass =
mysql_query("UPDATE members SET pass='".md5($_POST['passwordnew1']).
"' WHERE username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
The first inner line already performs the mysql_query and returns a resource, which is assigned to $querynewpass.
You're resending the result (a resource) to another query, as if it was a string containing the SQL command you want to perform.
This is the function's specification:
resource mysql_query ( string $query [, resource $link_identifier = NULL ] )
This is the correct usage of mysql_query (which is deprecated as people mentioned):
if($row['username'])
{
$querynewpass =
"UPDATE members SET pass='".md5($_POST['passwordnew1']).
"' WHERE username='{$_SESSION['username']}'";
$result = mysql_query($querynewpass) or die(mysql_error());
}
This code snippet could help to you
$pass1 = md5(mysql_real_escape_string($_POST['password1']));
$newpass = md5(mysql_real_escape_string($_POST['passwordnew1']));
$username = mysql_real_escape_string($_SESSION['username'])
$query = "SELECT id,username FROM members WHERE username = '$username' AND pass = '$pass1'";
$result = mysql_query($query); //that could also use , mysql_query($query,$yourconnection);
if(mysql_num_rows($result)>0)
{
$updatequery = "UPDATE members SET pass='$newpass' WHERE username='$username'";
$updateresult = mysql_query($updatequery) or die(mysql_error());
}
Please note that mysql library is deprecated in after php ver 5.5.0

PHP form search for MySQL DB

I need some help getting a search function to work. I have previously coded something to work similar to this, where if I click on a hyperlink, I'm able to carry a variable forward and then assign this into an SQL script so it pulls only this one thing back from the DB. (Predefined variable, and not user input). I've tried modifying the script I've been using to allow for a form based text box to have user input which is then searched through a single database field, with a LIKE statement.
This is what I have, and it's not returning anything.
Input Form
<form class="formFormat" method="post" action="SearchResult.php">
<label class="lableInput2">Key Words</label>
<input type="text" class="textInput" name="JobDetails" />
<input type="image" src="img/blue/buttonsearch.jpg" value="search" class="buttonInput" alt="Submit Form" border="0" />
</form>
Returning Page
<?php
include('conn_mysql.inc');
include('corefuncs.php');
// create database connection
$conn = dbConnect('query');
// initialize flag
$deleted = false;
// get details of selected record
if ($_GET && !$_POST) {
// check that primary key is numeric
if (isset($_GET['JobDetails']) && is_numeric($_GET['JobDetails'])) {
$JobDetails = $_POST['JobDetails'];
}
else {
$JobDetails = NULL;
}
if ($JobDetails) {
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($result);
}
}
?>
<p><h1><?php echo ($row['JobTitle'].'<span class="jobid"> #'.$row['IDJobs'].'</span>');?></h1></p>
<p><strong><?php echo ($row['Location']); ?></strong></p>
<p><strong>£<?php echo ($row['JobValue']); ?>.00</strong></p>
<p><strong>www.companyurl.com - BAD IDEA?</strong></p>
<p><strong>Open for Bidding</strong></p>
<br />
<p><span class="jobid">Job Posted: <?php echo ($row['JobPostDate']); ?></span></p>
<p><?php print ($row['JobDetails']); ?></p>
<p><span class="jobid">Job Deadline: <?php echo ($row['JobDeadline']); ?></span></p>
I know that I need to loop the output, so it displays more than one, but at the moment it simply returns the following error for every field (obv the line changes depending on what's trying to extract.
"( ! ) Notice: Undefined variable: row in
C:\wamp\www\ReEmployWork\SearchResult.php on line 54"
Can anyone assist? I'm a bit lost with this, and I believe I'm either going in the wrong direction or just missing something.
You missed $ before the variable name. Instead of:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
write:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$JobDetails%'";
You left your $ before JobDetails in you query.
Also remeber to use http://php.net/manual/en/function.mysql-real-escape-string.php
A suggestion:
$escaped_value = mysql_real_escape_string($JobDetails)
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$escaped_value%'";
For future readers. I scrapped the code I tried to modify and I took it from the beginning. There's enough information above for anyone to do this. Have a go, and you may end up with a result similar to what I coded.
$JobDetails = $_POST['JobDetails'];
$JobDetails = mysql_real_escape_string($JobDetails);
$sql = "SELECT * FROM `jobs` WHERE `JobDetails` LIKE '%{$JobDetails}%'";
$result = mysql_query($sql) or die (mysql_error());
?>
The above is what I coded and it runs like a dream. You make a lot more mistakes modifying code than you do, if you just code from scratch, so if you're learning dabble and play with code already wrote, but if you need something yourself which is unique then you're best starting from scratch.

php select to get a variable and then apply if else on it

I have a car rental system I am working on. When a user rents a car, the system should first check if the number of available cars is greater than 0, if yes, then make the adjustment "AVAILABLE = AVAILABLE+1" (in the MySQL table which keeps track of cars), which means, rent the car to the user. Also, I am trying to record which car went to which user. So I have another database table called rentalrecords which takes in the values of the Username of the logged in user, and ID of the car rented. Now, the problem is, my 'IF-ELSE' part is not executing as desired.
<div id="stylized" class="myform">
<form id="form" name="form" method="POST" action="renting.php" >
<h1>Rent a Car</h1>
<label>Car ID
<span class="small">eg. Enter 1 for Mer1</span>
</label>
<input type="text" name="ID" id="ID" />
<input type="submit" style="margin:30px 100px;" name="submit" value="Check-Out">
<div class="spacer"></div>
</form>
</div>
Now,the action of this form, which is renting.php, is as follows:
<?php
session_start();
if(!session_is_registered(theUSERNAME)){
header("location:customer_login.php");
}
mysql_CONNECT("xx", "xx", "xx") OR DIE("Unable to connect");
mysql_SELECT_DB("xx") OR DIE("Unable to select database");
$ID = $_POST['ID'];
$result = mysql_query("SELECT AVAILABLE FROM car WHERE ID='$ID'");
if(mysql_fetch_array($result)>0)
{
$query="UPDATE car SET AVAILABLE=AVAILABLE-1 WHERE ID='$ID'";
mysql_query($query);
$query = "insert into rentalrecords (USERNAME,ID,RENTED_ON) values ('$_SESSION[theUSERNAME]','$_POST[ID]',CURDATE())";
$result = mysql_query($query);
header("location: list_Clogged.php");
}
else
{
echo "<script>alert('The car you chose is currently unavailable!'); location.href='rent.php';</script>";
}
?>
Even though I have available=0, it still is NOT executing the else part and no matter what, it always executes the IF part. The ID and AVAILABLE are the attributes of my MySQL table called 'car' and the in rental records table i just want to insert these values. I am aware that the script is vulnerable to injection at the moment, but first I want to get things working! Any immediate help would be much appreciated.
You're trying to count a resource...
if(mysql_fetch_array($result)>0)
You need to obtain the results and then count an item within those results:
$res = mysql_fetch_assoc($result);
if($res[0]['AVAILABLE'] > 0)
Note $res[0] means first row of the results. You can also use mysql_fetch_row to obtain a single result.
Keep in mind, mysql_ functions shouldn't be used at all. Look into switching to mysqli or PDO.
Also, you need to sanitize input. You're just blindly accepting $_POST['ID']
The mysql_fetch_array function doesn't do what you think it does; it returns an array, not a single value.

Categories