PHP and MySQL form, what am I doing wrong? - php

I have a table that has the user ID already in it, but some of the information is missing and that is where I need the user to input it themselves. With the URL of the form I have their ID in it... winnerpage.php?ID=123
I am having troubles getting the code to work. Any help would be great!
This is the code on that winnerpage.php
<form enctype="multipart/form-data" action="winnerpage.php" method="POST">
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
First Name: <input type="text" name="FN"><br />
Last Name: <input type="text" name="LN"><br />
Email: <input type="text" name="EM"><br />
Phone: <input type="text" name="PH"><br />
<input type="submit" name="edit" value="edit"></form> <br>
<?
require_once('mysql_serv_inc.php');
$conn = mysql_connect("$mysql_server","$mysql_user","$mysql_pass");
if (!$conn) die ("ERROR");
mysql_select_db($mysql_database,$conn) or die ("ERROR");
if(isset($_POST['edit']))
{
$sID = addslashes($_POST['ID']);
$sFN = addslashes($_POST['FN']);
$sLN = addslashes($_POST['LN']);
$sEM = addslashes($_POST['EM']);
$sPH = addslashes($_POST['PH']);
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH
WHERE ID=$sID') or die (mysql_error());
echo 'Updated!';
}
$query = "select * from winner order by ID";
$result = mysql_query($query);
?>
<?
while ($link=mysql_fetch_array($result))
{
echo 'Unique ID - Completion Time - First Name - Last Name - Email - Phone<br/>'.$link[ID].' -' .$link[FN].' - '.$link[LN].' - '.$link[EM].' - '.$link[PH].'<br>';
}
?>

1)
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
Where do you get that $ID? Are you doing something like $_GET['ID'] or are you relying on safe_mode being ON? (it's not clear from the code you provided)
(better yet, if(isset($_GET['ID'])) { $ID = (int)$_GET['ID'] }
2) Please don't to that. Don't use addslashes(). Use mysql_real_escape_string() or, even better, prepared statements. Addslashes is not utterly reliable in escaping datas for queries.
sID = (int)$_POST['ID'];
$sFN = mysql_real_escape_string($_POST['FN']);
$sLN = mysql_real_escape_string($_POST['LN']);
$sEM = mysql_real_escape_string($_POST['EM']);
$sPH = mysql_real_escape_string($_POST['PH']);
Also, add 'value=""' to each input field (not mandatory)
3) encapsulate values in query:
mysql_query("UPDATE winner SET FN='".$sFN."', LN='".$sLN."', EM='".$sEM."', PH='".$sPH."' WHERE ID='".$sID."'") or die (mysql_error());

Maybe try:
mysql_query("UPDATE winner SET FN='$sFN', LN='$sLN', EM='$sEM', PH='$sPH' WHERE ID=$sID") or die (mysql_error());

mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH WHERE ID=$sID')
the query is encapsulated by single-quotes, so the variables inside will not be parsed.

At first glance I would say that you need:
1) Quote marks around some of the values you are inserting into the table (any strings for example)
2) Quote marks around the names of the fields when you try to echo them out at the end ($link['ID'] for example)

Related

Update certain column of recordset from textbox value

room.php
<input name = "room" type = "text" size="70"/>
Update
updateroom.php
<?php
mysql_connect('localhost','athirahhazira','1234');
mysql_select_db("dbcollege");
session_start();
$sql = "UPDATE studentsroom set room='$strroom' WHERE roomid='$_GET[roomid]'";
mysql_query($sql) or die('Error updating room status');
header('Location:staff/room-staff.php');
?>
i can update if there is a default value such as :
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='$_GET[roomid]'";
but not the value from a textbox. could u help me with what i am missing here?
try this
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='".$_REQUEST['roomid']."'";
Note: your code can be sql injection. also mysql_* is deprecated use mysqli_* or PDO
Update2:
add a form and submit button instead of hyperlink
<form method="post" action="updateroom.php" >
<input name = "room" type = "text" size="70"/>
<input type="hidden" name="roomid" value="<?php echo $row_Recordsetroomid['roomid'];?>" />
<input type="submit" name="submit" value="Update" />
</form>
AND update.php
<?php
mysql_connect('localhost','athirahhazira','1234');
mysql_select_db("dbcollege");
session_start();
$room = $_REQUEST['room'];
$roomid = $_REQUEST['roomid'];
$room = mysql_real_escape_string($room);
$roomid = mysql_real_escape_string($roomid);
$sql = "UPDATE studentsroom set room='$room' WHERE roomid='$roomid'";
mysql_query($sql) or die('Error updating room status');
header('Location:staff/room-staff.php');
?>
The quotes for the index in the $_GET is missing. Trying to access array variables like $array[key] instead of $array['key'], will trigger an error in most cases. So always try to use quotes for array indexes.
You can try with this.
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='".$_GET['roomid']."'";

Form processing won't pass value

i have this code which permits me to do a request in order to make a query!
Now the form which is processed has this code:
<form action="edit_images.php" method="post">
<input type="hidden" value="<? echo $gal_id1 ?>" name="img_id1" />
<input type="submit" value="Edit All Images" />
</form>
While the query is like this :
$img_id=$_REQUEST['img_id1'];
$sql="SELECT * FROM tbl_images WHERE Img_gal_id='$img_id'";
But it seems like it won't take the value...
I mean, it doesn't recognize the $img_id, which i have printed before and takes the exact value.
Let me show you the query i use in order to retrieve it:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
if(isset($myErrors) && $myErrorsP!=''){
} else {
$row = mysql_fetch_row($query);
mysql_free_result($query);
$gal_id = $row[0];
$gal_id1 = $row[0];
$gal_title = $row[1];
$gal_image = $row[2];
}
You are missing a ; on the end of your echo that isn't outputting the value as expected. Additionally, you are using short tags, which could be causing problems. You might want to swtich to using <?php as an opening over <? on it's own.
<input type="hidden" value="<?php echo $gal_id1; ?>" name="img_id1" />
Lastly, you are using zero protection against injection attacks. Please, research prepared statements in PDO and update your code. The first injection attack you don't have will thank you for it.
Edit: When you run into a problem like this, it is often good practice to echo out the $sql just before you execute it.
you could do this in the future with:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
echo $sql."<br>\n";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
which would have probably given you an excellent indication of what the problem was.

Update query PHP MySQL [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
PHP UPDATE prepared statement
(3 answers)
Closed 11 months ago.
Can anybody help me understand why this update query isn't updating the fields in my database? I have this in my php page to retrieve the current values from the database:
<?php
$query = mysql_query ("SELECT * FROM blogEntry WHERE username = 'bobjones' ORDER BY id DESC");
while ($row = mysql_fetch_array ($query))
{
$id = $row['id'];
$username = $row['username'];
$title = $row['title'];
$date = $row['date'];
$category = $row['category'];
$content = $row['content'];
?>
Here i my HTML Form:
<form method="post" action="editblogscript.php">
ID: <input type="text" name="id" value="<?php echo $id; ?>" /><br />
Username: <input type="text" name="username" value="<?php echo $_SESSION['username']; ?>" /><br />
Title: <input type="text" name="udtitle" value="<?php echo $title; ?>"/><br />
Date: <input type="text" name="date" value="<?php echo $date; ?>"/><br />
Message: <textarea name = "udcontent" cols="45" rows="5"><?php echo $content; ?></textarea><br />
<input type= "submit" name = "edit" value="Edit!">
</form>
and here is my 'editblogscript':
<?php
mysql_connect ("localhost", "root", "");
mysql_select_db("blogass");
if (isset($_POST['edit'])) {
$id = $_POST['id'];
$udtitle = $_POST['udtitle'];
$udcontent = $_POST['udcontent'];
mysql_query("UPDATE blogEntry SET content = $udcontent, title = $udtitle WHERE id = $id");
}
header( 'Location: index.php' ) ;
?>
I don't understand why it doesn't work.
You have to have single quotes around any VARCHAR content in your queries. So your update query should be:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");
Also, it is bad form to update your database directly with the content from a POST. You should sanitize your incoming data with the mysql_real_escape_string function.
Need to add quote for that need to use dot operator:
mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");
Without knowing what the actual error you are getting is I would guess it is missing quotes. try the following:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = '$id'")
Here i updated two variables and present date and time
$id = "1";
$title = "phpmyadmin";
$sql= mysql_query("UPDATE table_name SET id ='".$id."', title = '".$title."',now() WHERE id = '".$id."' ");
now() function update current date and time.
note: For update query we have define the particular id otherwise it update whole table defaulty
First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.
Try like this in sql query, It will work fine.
$sql="UPDATE create_test set url= '$_POST[url]' WHERE test_name='$test_name';";
If you have to update multiple columns,
Use like this,
$sql="UPDATE create_test set `url`= '$_POST[url]',`platform`='$_POST[platform]' WHERE test_name='$test_name';";
you must write single quotes then double quotes then dot before name of field and after like that
mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");

Can I use $_POST & $_GET at the same time?

I have a following form:
<form action="doThis.php?warehouse=12" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
</form>
And doThis.php:
$field1 = mysql_real_escape_string($_POST['field1'], $mysql);
$field2 = mysql_real_escape_string($_POST['field2'], $mysql);
$warehouse = $_GET['warehouse'];
if ( !someTableNameValidation($warehouse) ) {
someErrorHandling();
}
$qry = "INSERT INTO table".$warehouse." ( field1, field2 ) VALUES( '$field2', '$field2') ";
$result = #mysql_query($qry, $mysql);
As you can see, I'm using $_POST to get data from the form, and $_GET to get variable $warehouse which is used to indicate table number.
Can I use both $_POST & $_GET at the same time? Is this kind of usage correct?
Yes you could. $_GET['warehouse'] will be taken from the query string, $_POST variables from submitted POST values.
Yes, this is possible. But you could also use a hidden field:
<form action="doThis.php">
<input type="hidden" name="warehouse" value="12" />
<input name="field1" type="text" />
<input name="field2" type="text" />
Please be aware that your code is very vulnerable to sql injections!
Yes I always do that.
Also note you should never use mysql_query. Search for php PDO. Not to mention the awful # for suppressing error
Yes, however it should be:
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$warehouse = $_GET['warehouse'];
$qry = "INSERT INTO table".$warehouse." ( field1, field2 ) VALUES ('".mysql_real_escape_string($field2)."', '".mysql_real_escape_string($field2)."')";
$result = #mysql_query($qry);
(Fixed syntax)
I frequently use POST and GET together, so that the PHP side can know whether it was a normal form submission or via AJAX.
<form action='dest.php'>
.
.
.
vs
ajaxSubmit( 'dest.php?a=1', ... );

how to post two field values in one variable

I have two fields
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
how to post name and lastname in one variable meaning in one field of database
is it
<?php
$name=$_post['firstname']['lastname'];
?>
Actually you have three fields. Use string concatenation (or implode):
$name = $_POST['firstname'] . ' ' . $_POST['lastname'];
And don't forget to use mysql_real_escape_string (or what #ThiefMaster says) if you store the values in a database. Never trust user input.
Just concatenate the two values e.g.
<?php
$name = $_POST['firstname'] . $_POST['lastname'];
?>
keep an array, and serialize it to store it.
$name['firstname']=$_post['firstname'];
$name['lastname']=$_post['lastname'];
//storage and retrieval methods
$stored_name = serialize($name);
$name = unserialize($stored_name);
This way you don't lose the functionality of having the variables separate in an array, and you can always concatenate them later for display if you need to.
You can give the text inputs the same name with []
Firstname: <input type="text" name="name[]" />
Lastname: <input type="text" name="name[]" />
then you can
$name = $_POST['name'][0].$_POST['name'][1];
but i would prefer
$name=$_post['firstname'] . ' ' . $_post['lastname'];
This One will help You...! I also implemented this and it works...!
Firstname: <input type="text" name="firstName" />
Lastname: <input type="text" name="lastName" />
$fullname = $_post['firstName']. ' ' .$_post['lastName'];
$name = $firstname . " " . $lastname;
Then post $name in whatever field you want.
I had this same problem, i have a form with the name of the person reporting the issue and it takes the first name and the last name from my database of users and adds them together, but then when it came time to post both names to the database it would only post the first name.
my solution was to first of all call the first name and last name from the database of users, then i called just the first name and last name and concat them together to produce reportername.
so this is the first part of the code calling for the user details i require for the form:
// Select the member from the users table
$sql = "SELECT * FROM users WHERE username='$log_username' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
// exit();
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$profile_id = $row["id"];
$first_name = $row["First_Name"];
$last_name = $row["Last_Name"];
$userlevel = $row["userlevel"];
}
Next i Concat the first name and last name:
$reporter_sql = "SELECT CONCAT (First_name,' ', Last_name) AS reportername FROM users WHERE username='$log_username' AND activated='1' LIMIT 1";
$reporter_results = mysqli_query($db_conx, $reporter_sql);
while ($row = mysqli_fetch_array($reporter_results, MYSQLI_ASSOC)){
$reportername = $row['reportername'];
}
then you can post it to your database:
$reportername = mysqli_real_escape_string($db_conx, $reportername);
$sql = "INSERT INTO yourform (`reportedby`) Value ('$reportername')";
I have striped my code down so it gives you an idea and I'm sure coders with more experience could tell you a simpler way to do this i just know it worked for me.
A shortcut way to concatenate variables is this:
$name = "$_POST[first_name] $_POST[last_name]"
General comment. A good proportion of the world don't have first and last names.
Better practice is just to ask for "Name", and stick it in one field.
If you must split 'em, then "given name" and "family name" are better labels.

Categories