I'm passing an id from a URL from the previous page and then try to update database values in the row of that id. I feel like I'm close. I'm able to update the value librarian_fname when I add into the update query the specific id number, but when I try and pass that value through the code, it must not be picking it up because it won't update when I use id = '$id'. Not sure what I'm doing wrong. And I am still learning so forgive me if this isn't perfect.
<?php
$id = $_GET['id'];
echo $id;
?>
<?php
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
foreach ($params as &$var) {
// check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
unset($var);
}
}
// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);
$librarian_fname = $_POST['librarian_fname'];
$id = $_POST['id'];
?>
<?php
if(isset($_POST['add'])) {
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = "UPDATE table SET librarian_fname = '$librarian_fname' WHERE id = '$id'";
mysql_select_db('Events');
$result = mysql_query( $sql, $conn );
if(! $result ) {
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
header("Location: search.php");
}
else {
?>
<?php
// define variables and set to empty values
$librarian_fname = $id = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$librarian_fname = test_input($_POST["librarian_fname"]);
$id = test_input($_POST["id"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
<legend><b>Appointment Topic</b></legend>
<input type="hidden" name="id" value="<? echo $id; ?>">
<label for="librarian_fname">First Name <em>*</em></label>
<input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> input name = "add" type = "submit" id = "add" value = "Submit">
</form>
<?php
}
?>
Try this
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
<legend><b>Appointment Topic</b></legend>
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
<label for="librarian_fname">First Name <em>*</em></label>
<input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> <input name = "add" type = "submit" id = "add" value = "Submit">
<input type="reset" name="resetButton" id="resetButton" vvalue="Reset Form" style="margin-right: 20px;" />
</form>
I think one of the issues may be that TABLE is a MySQL reserved word.
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
If we want to use a reserved word as an identifier (e.g. table name) it must be escaped. The normative pattern in MySQL to escape identifiers is to enclose them in single backtick characters, e.g.
UPDATE `table` SET
That works whether the identifier is a reserved word or not. Better would be to use a different name for the table.
Be aware that the code appears to be vulnerable to SQL Injection. Potentially unsafe values incorporated into the text of a SQL statement must be properly escaped (e.g. using mysqli_real_escape_string)
https://xkcd.com/327/
The preferred pattern is to not incorporate values into the SQL text, and instead use a prepared statement with bind placeholders.
Related
I am trying to edit form data by displaying the previous saved data on the form and then update it. It shows the data on the form which is saved in database but when i enter the new data it does not get the id of the row. I echo the update query, it shows the changed values but it shows id equals to empty. Here is my code for edit record and update; Edit record is working but update isn't:
<?php
include('connection.php');
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
$udfname = mysql_real_escape_string($_POST["udfname"]);
$udlname = mysql_real_escape_string($_POST["udlname"]);
$udpwd = mysql_real_escape_string($_POST["udpwd"]);
$udeml = mysql_real_escape_string($_POST["udeml"]);
$udnum = mysql_real_escape_string($_POST["udnum"]);
$query="UPDATE form
SET fname = '$udfname', lname = '$udlname', pwd = '$udpwd', eml = '$udeml', num = '$udnum'
WHERE id='$id'";
$res= mysql_query($query);
if($res){
echo "<p> Record Updated<p>";
}else{
echo "Problem updating record. MY SQL Error: " . mysql_error();
}
?>
Form for editing record:
<?php
include('connection.php');
$id = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM form WHERE id = '$id'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo "";
$fname = $row['fname'];
$lname = $row['lname'];
$pwd = $row['pwd'];
$eml = $row['eml'];
$num = $row['num'];
}
?>
<html>
<head>
<title>Edit</title>
<script>
'
'
Jquery code here
'
'
</script>
</head>
<body>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$id;?>">
First Name: <input type="text" name="udfname" value="<?=$fname;?>"><br>
Last Name: <input type="text" name="udlname" value="<?=$lname?>"><br>
Password: <input type="text" name="udpwd" value="<?=$pwd?>"><br>
Email: <input type="text" name="udeml" value="<?=$eml?>"><br>
Contact Number: <input type="text" name="udnum" value="<?=$num?>"><br>
<input type="Submit">
</form>
</body>
</html>
At update time your form is submitted using POST request. So you need to get ID using POST method. So to get ID of hidden field change your code as below:
$id = '';
if( isset( $_POST['ID'])) {
$id = $_POST['ID'];
}
Please try below code
if( isset( $_POST['id']) && $_POST['id']!=null) {
$id = $_POST['id'];
}
Dear i think the problem with your method you are sending the data using post method and its very simple instead of this code
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
write
if( isset( $_POST['id'])) {
$id = $_POST['id'];
}
and one more thing that is you are using the mysql deprecated function for database kindly use the pdo for this or new mysqli functions.
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;
}
?>
I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php
I'm creating an edit user profile for my project. I came across this error "
Notice: Undefined index: userid in C:\xampp\htdocs\HelloWorld\EditProfile.php on line 18
". I've spent an hour trying to find the cause of the error but I can't seem to find it. I followed this guide here php -'Edit' function for forum posts and such Here's my code:
EditProfile.php
<?php
// connect to SQL
$dbcnx = mysql_connect("localhost", "root", "2345fypj");
if (!$dbcnx)
{
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = mysql_select_db("my_db", $dbcnx);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
//data preparation for the query
$id = intval($_GET['userid']);
// selects title and description fields from database
$sql = "SELECT * FROM user_profile WHERE userid=$id";
$result = mysql_query($sql) or die(mysql_error());
# retrieved by using $row['col_name']
$row = mysql_fetch_array($result);
?>
<h3>Edit</h3>
<form action="save_edit.php" enctype="multipart/form-data" method="post" name="myForm" />
<table>
<tr>
<td><b>Name</b></td>
<td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['name'] ?>"></td>
</tr>
<tr>
<td><b>Age</b></td>
<td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['age'] ?>"></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input name="enter" type="submit" value="Edit">
</form>
<?php
mysql_close($dbcnx);
?>
save_edit.php
<?php
// connect to SQL
$con = mysql_connect("localhost", "root", "2345fypj");
if (!$con) {
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = #mysql_select_db("user_profile", $con);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
#data preparation for the query
$id = intval($_POST["userid"]);
foreach ($_POST as $key => $value) $_POST[$key] = mysql_real_escape_string($value);
$sql = "UPDATE user_profile SET
name='$_POST[name]',
age='$_POST[age]',
WHERE userid=$id";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
header ("location: http://www.domain.com/url_to_go_to_after_update");
?>
Thanks in advance.
$id = intval($_GET['userid']);
It means set the $id variable to the "userid" variable in your URL. For example, if your URL is mySite.com?userid=12, $id will be set to "12". if your URL doesn't have "username=aValue" at the end section of it, you'll get the error you're seeing. :)
You could change it to this to set a default value:
$id = (isset($_GET['userid']) ? intval($_GET['userid']) : -1);
The problem is you're trying to use variable $_GET['userid'] while it's undefined. This variable refers to GET parameter in URL (e.g. EditProfile.php?userid=42). If this parameter isn't passed in URL, you will get this warning. You should check existence of variable:
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$id = intval($_GET['userid']);
You should probably be sure that the value is correctly set before trying to access it. Try using the isset function beforehand.
http://php.net/manual/en/function.isset.php
The problem with your code is apart from using a variable before its used, your continuing todo the query when setting to a default value with intval (will always return atleast 0), which if a non numeric character is passed your always going to update the row 0 user in the table, what you should be doing is not updating anything and returning the user with an error. You also have a rouge , after you age column in the query.
<?php
if(isset($_POST["userid"]) && is_numeric($_POST["userid"])){
$_POST = array_walk($_POST,'mysql_real_escape_string');
$sql = "UPDATE `user_profile` SET `name`='{$_POST['name']}', `age`='{$_POST['age']}'
WHERE `userid` = {$_POST['userid']}";
mysql_query($sql);
}else{
header('Location: ./failed');
}
?>
I have a page called index.html which takes in a few variable from the user, when the user submits them, it goes to the next page (result.php) On results.php the variables from the form on the index.html are posted. The results.php connects to database runs a query etc. All of this works fine. the results.php looks something like this:
<?php
$h = "localhost";
$u = "root";
$p = "******";
$d = "********";
//connectipn to mysql
$conn = mysql_connect( $h, $u, $p );
//connection to database
mysql_select_db($d);
$code = $_POST['code'];
$usage = $_POST['usage'];
$days = $_POST['days'];
$value = $_POST['value];
$sql_runners_up = "SELECT code
from some_table
where number = $value;"
$plans['p_h10'] = array();
$rs2 = mysql_query( $sql_runners_up, $conn );
while ( $row = mysql_fetch_array( $rs2 ))
{
$plans['p_h10'][] = $row["p_h10"];
}
?>
The results.php also has a form that the user can update some fields that are used in the query. the form that I currently have looks like this...
<form action="results.php" name="filter" method="post">
usage:<input name="" type="search" value="" /><br/>
days:<input name="" type="search" value="" /><br/>
<input name="" type="checkbox" value="" />value<br />
<input type="submit" value="submit" name="submit" />
</form>
Even with a blank as soon as the user submits the form I get an error (i have tried filling out the form to use real variable but still get the same error)
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource
the error refers to the line around the while statement. my guess is that some variable/s are not being passed after the form is submitted or the entire results.php form is not being submitted / processed by the server. But to be honest I am really not sure. Any help will be greatly appreciated.
That's because mysql_query returned false.
Also, in your code, you've got a syntax error
$value = $_POST['value'];
Also, your code is vulnerable. Don't trust user's input!
so, correct code would be
$value = intval($_POST['value']);
Try:
$value = (int) $value;
$sql_runners_up = "SELECT code from some_table where number = $value";
$plans['p_h10'] = array();
$rs2 = mysql_query( $sql_runners_up);
try with this:
$sql_runners_up = "SELECT * from some_table where number = '$value';"
and also check that the $value has containing the value..
EDIT: in the above code i use * which select all the fields, cause that is see in your code you did:
$sql_runners_up = "SELECT code from some_table where number = $value;"
and in fetch query you are calling to field name p_h10:
while ( $row = mysql_fetch_array( $rs2 ))
{
// didn't selected $row["p_h10"] in your query
$plans['p_h10'][] = $row["p_h10"];
}
First of all, this row is invalid:
$value = $_POST['value];
It should be $_POST['value'];
But, this error occurs usually when there is an error in your query, or the connection is bad. Check your mysql_connect() & mysql_select_db() settings, it is probably bad.
looks like you did typos...
<?php
$h = "localhost";
$u = "root";
$p = "******";
$d = "********";
//connectipn to mysql
$conn = mysql_connect( $h, $u, $p );
//connection to database
mysql_select_db($d);
$code = $_POST['code'];
$usage = $_POST['usage'];
$days = $_POST['days'];
$value = $_POST['value']; // here
$sql_runners_up = "SELECT code
from some_table
where number = $value"; // and here
$plans['p_h10'] = array();
$rs2 = mysql_query( $sql_runners_up, $conn );
while ( $row = mysql_fetch_array( $rs2 ))
{
$plans['p_h10'][] = $row["p_h10"];
} ?>
also your form is not POSTing parameters... because name attributes are not set
<form action="results.php" name="filter" method="post">
usage:<input name="usage" type="search" value="" /><br/>
days:<input name="days" type="search" value="" /><br/>
<input name="value" type="checkbox" value="" />value<br />
<input type="submit" value="submit" name="submit" />
</form>