Website form not submitting data to mssql database - php

I have spent days trying to figure how to get form data on my webpage to insert into my employee table on the forklift database mssql. when i click submit on the form it refreshes the page with Connection established but no data in the database.
<?php
/* Connect using Windows Authentication. */
$serverName = "EXAMPLE";
$connectionOptions = array("Database"=>"FORKLIFT");
/* Connect using Windows Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if($conn)
{
echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die(print_r(sqlsrv_errors(), true));
}
if(empty($_POST) === false && empty($errors)=== true)
{
//assign form input to variables
$FIRSTNAME = $_POST["FIRSTNAME"];
$LASTNAME = $_POST["LASTNAME"];
$DATEOFBIRTH = $_POST["DATEOFBIRTH"];
$PHONENUMBER = $_POST["PHONENUMBER"];
$ADDRESS = $_POST["ADDRESS"];
/*Insert data.*/
$INSERT_ROW = $query = "INSERT INTO
EMPLOYEE(FIRSTNAME,LASTNAME,DATEOFBIRTH,PHONENUMBER,ADDRESS)
VALUES ('$FIRSTNAME','$LASTNAME','$DATEOFBIRTH','$PHONENUMBER','$ADDRESS')";
$result = sqlsrv_prepare($conn,$query)or die('Error querying MSSQL
database');
sqlsrv_execute($result);
}
?>
HTML
<form name="submit" action="employee.php" method="POST" >
<h2>Register New Member</h2>
<table border="0">
<tr>
<td>FIRSTNAME</td>
<td>
<input type="text" name="FIRSTNAME" id="FIRSTNAME"/>
</td>
</tr>
<tr>
<td>LASTNAME</td>
<td>
<input type="text" name="LASTNAME" id="LASTNAME"/>
</td>
</tr>
<tr>
<td>DATE_OF_BIRTH</td>
<td>
<input type="date" name="DATE_OF_BIRTH" id="DATE_OF_BIRTH"/>
</td>
</tr>
<tr>
<td>PHONENUMBER</td>
<td>
<input type="text" name="PHONENUMBER" id="PHONENUMBER"/>
</td>
</tr>
<tr>
<td>ADDRESS</td>
<td>
<input type="text" name="ADDRESS" id="ADDRESS"/>
</td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" name="submit" value="REGISTER"/></td>
</tr>
</table>

I noticed that you are attempting to post data to a database, that is not actually named correctly on the PHP side, this would just result in the information related to your DATE OF BIRTH not being posted in the first place, as it has to match the PHP side exactly when you declare to retrieve posted data. I am pretty sure from memory that you only need to change the name in the form on the client side to DATEOFBIRTH, or you will have to change the PHP side to DATE_OF_BIRTH instead of this, whilst keeping the client side as DATE_OF_BIRTH
<input type="date" name="DATE_OF_BIRTH" id="DATE_OF_BIRTH"/>
NEEDS TO BE:
<input type="date" name="DATEOFBIRTH" id="DATEOFBIRTH"/>

I made a couple of minor alterations but cannot test to see - run it and see what the resultant sql statement looks like. I hope it helps.
<?php
if( !empty( $_POST ) && isset( $_POST["FIRSTNAME"], $_POST["LASTNAME"], $_POST["DATE_OF_BIRTH"], $_POST["PHONENUMBER"], $_POST["ADDRESS"] ) ) {
/*
There is no point creating a db connection if a later condition fails
so create the db conn after testing key variables are set
*/
$server = "EXAMPLE";
$options = array( "Database"=>"FORKLIFT" );
$conn = sqlsrv_connect( $server, $options );
/* In production environment do not display actual errors! */
if( !$conn ) die( print_r( sqlsrv_errors(), true ) );
/* as pointed out by #Daniel Rutter, the field is actually called `DATE_OF_BIRTH` */
$FIRSTNAME = $_POST["FIRSTNAME"];
$LASTNAME = $_POST["LASTNAME"];
$DATEOFBIRTH = $_POST["DATE_OF_BIRTH"];
$PHONENUMBER = $_POST["PHONENUMBER"];
$ADDRESS = $_POST["ADDRESS"];
$sql = "INSERT INTO EMPLOYEE
( FIRSTNAME,LASTNAME,DATEOFBIRTH,PHONENUMBER,ADDRESS )
VALUES
( '$FIRSTNAME','$LASTNAME','$DATEOFBIRTH','$PHONENUMBER','$ADDRESS' )";
/* Comment out the following line after running the script and observing the output here */
exit( $sql );
/* I assume that `sqlsrv_prepare` returns either true or false */
$stmt = sqlsrv_prepare( $conn, $sql ) or die( 'Error querying MSSQL database' );
if( $stmt ) sqlsrv_execute( $stmt );
/* debug post vars */
} else { echo 'Error::' . print_r($_POST,true ); }
?>
Having briefly had a look at the online PHP manual for the various sqlsrv_* commands perhaps you ought to try along these lines - it follows closely with one of the examples given - though it is untested due to not having a mssql server instance to play with.
<?php
if( !empty( $_POST ) && isset( $_POST["FIRSTNAME"], $_POST["LASTNAME"], $_POST["DATE_OF_BIRTH"], $_POST["PHONENUMBER"], $_POST["ADDRESS"] ) ) {
/*
There is no point creating a db connection if a later condition fails
so create the db conn after testing key variables are set
*/
$server = "EXAMPLE";
$options = array( "Database"=>"FORKLIFT" );
$conn = sqlsrv_connect( $server, $options );
/* In production environment do not display actual errors! */
if( !$conn ) die( print_r( sqlsrv_errors(), true ) );
$FIRSTNAME = $_POST["FIRSTNAME"];
$LASTNAME = $_POST["LASTNAME"];
$DATEOFBIRTH = $_POST["DATE_OF_BIRTH"];
$PHONENUMBER = $_POST["PHONENUMBER"];
$ADDRESS = $_POST["ADDRESS"];
$sql = "INSERT INTO EMPLOYEE
( FIRSTNAME, LASTNAME, DATEOFBIRTH, PHONENUMBER, ADDRESS )
VALUES
( ?,?,?,?,? )";
$params=array(
&$FIRSTNAME,
&$LASTNAME,
&$DATEOFBIRTH,
&$PHONENUMBER,
&$ADDRESS
);
/* add the posted variables as an array here as the third arg */
$stmt = sqlsrv_prepare( $conn, $sql, $params ) or die( 'Error querying MSSQL database' );
if( $stmt ) sqlsrv_execute( $stmt );
/* debug post vars */
} else {
echo 'Error::' . print_r( $_POST, true );
}
?>
From the PHP online manual regarding sqlsrc_prepare:
Prepares a query for execution. This function is ideal for preparing a
query that will be executed multiple times with different parameter
values.
and
When you prepare a statement that uses variables as parameters, the
variables are bound to the statement. This means that if you update
the values of the variables, the next time you execute the statement
it will run with updated parameter values. For statements that you
plan to execute only once, use sqlsrv_query().

Related

Why every time f5(refresh) is my website insert data to the database

I have a form that inserts data into the database using mysql. When I click submit (add data) the data is inserted into the database successfully. However, when I press f5 (refresh), the data is still inserted into the database. I do not know where I'm wrong. Please help me. This is my code:
<?php
$username = "user_tintuc"; // Khai báo username
$password = "123456"; // Khai báo password
$server = "localhost"; // Khai báo server
$dbname = "tintuc"; // Khai báo database
// Kết nối database tintuc
$connect = new mysqli($server, $username, $password, $dbname);
//Nếu kết nối bị lỗi thì xuất báo lỗi và thoát.
if ($connect->connect_error) {
die("Không kết nối :" . $conn->connect_error);
exit();
}
//Khai báo giá trị ban đầu, nếu không có thì khi chưa submit câu lệnh insert sẽ báo lỗi
$title = "";
$date = "";
$description = "";
$content = "";
//Lấy giá trị POST từ form vừa submit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["title"])) { $title = $_POST['title']; }
if(isset($_POST["date"])) { $date = $_POST['date']; }
if(isset($_POST["description"])) { $description = $_POST['description']; }
if(isset($_POST["content"])) { $content = $_POST['content']; }
//Code xử lý, insert dữ liệu vào table
$sql = "INSERT INTO tin_xahoi (title, date, description, content)
VALUES ('$title', '$date', '$description', '$content')";
if ($connect->query($sql) === TRUE) {
echo "Thêm dữ liệu thành công";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
//Đóng database
$connect->close();
?>
<form action="" method="post">
<table>
<tr>
<th>Tiêu đề:</th>
<td><input type="text" name="title" value=""></td>
</tr>
<tr>
<th>Ngày tháng:</th>
<td><input type="date" name="date" value=""></td>
</tr>
<tr>
<th>Mô tả:</th>
<td><input type="text" name="description" value=""></td>
</tr>
<tr>
<th>Nội dung:</th>
<td><textarea cols="30" rows="7" name="content"></textarea></td>
</tr>
</table>
<button type="submit">Gửi</button>
</form>
I edited it like this. But it's still like that.
if (isset($_POST['submit'])){
if(isset($_POST["date"])) { $date = $_POST['date'];}
if(isset($_POST["MAB"])) { $MAB = $_POST['MAB']; }
if(isset($_POST["MBA"])) { $MBA = $_POST['MBA']; }
if(isset($_POST["PAB"])) { $PAB = $_POST['PAB']; }
if(isset($_POST["PBA"])) { $PBA = $_POST['PBA']; }
$sql = "INSERT INTO `dbsht` (`date`, `MAB`, `MBA`, `PAB`, `PBA`) VALUES ('$date', '$MAB', '$MBA', '$PAB', '$PBA')";
if ($connect->query($sql) === TRUE) {
echo "Thêm dữ liệu thành công";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
This is normal issues. You should use POST-Redirect-GET pattern to prevent it. After insert database successful, you should response with redirect to GET request.
You may try
if ($connect->query($sql) === TRUE) {
$_SESSION["ADD_SUCCESS"] = 1;
header('Location: '.$_SERVER['REQUEST_URI']);
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
For successful message
//Đóng database
$connect->close();
if(isset($_SESSION["ADD_SUCCESS"]))
{
echo "Chúc mừng bạn đã thêm dữ liệu thành công";
unset($_SESSION["ADD_SUCCESS"]);
}
You can fix it, but don't, reorganize it and rewrite it because your approach is border-line terrible.
Have myform.html as one file, your php code for inserting data in db as another file like db_insert.php and your data for db connection (user, pass, db, host) in separate file OUTSIDE of public folder (outside public_html or whatever) in file config.inc.php, for example. Do this and you'll avoid this problem that you have right now and many others.
So in myform.html enter data and submit => db_insert.php gets data from myform.html, fetches data from config.inc.php, enters it in DB and redirects back to myform.html or some other part of your application.
After you make it work and figure it out how and why, then read a few articles about AJAX and how to do the same job without leaving your form page. It's obvious that you just started learning, so make sure you learn it the right way ;)
Once the POST request has been sent the php code should do the necessary logic tests and sanitation routines on the data, construct and execute the sql and finally redirect to either the same page or another. The redirect will prevent the form being re-submitted when refreshing the page
<?php
$message='';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
$username = "user_tintuc";
$password = "123456";
$server = "localhost";
$dbname = "tintuc";
$connect = new mysqli( $server, $username, $password, $dbname );
$title = isset( $_POST["title"] ) ? $_POST["title"] : false;
$date = isset( $_POST["date"] ) ? $_POST["date"] : false;
$description = isset( $_POST["description"] ) ? $_POST["description"] : false;
$content = isset( $_POST["content"] ) ? $_POST["content"] : false;
if( $title && $date && $description && $content ){
$sql = 'insert into `tin_xahoi` ( `title`, `date`, `description`, `content`) values (?,?,?,?)';
$stmt=$connect->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ssss',$title,$date,$description,$content);
$result=$stmt->execute();
$stmt->close();
/* set a temporary session variable - used to display message */
$_SESSION['dbstatus']=$result ? 'Record added' : 'Sorry - an error occurred';
header('Location: ?status=' . ( $result ? 'ok' : 'error' ) );
} else {
throw new Exception('Failed to prepare sql');
}
} else {
throw new Exception('one or more variables are empty');
}
}catch( Exception $e ){
$message=sprintf('<p>%s</p>',$e->getMessage());
}
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<th>Tiêu d?:</th>
<td><input type="text" name="title" value=""></td>
</tr>
<tr>
<th>Ngày tháng:</th>
<td><input type="date" name="date" value=""></td>
</tr>
<tr>
<th>Mô t?:</th>
<td><input type="text" name="description" value=""></td>
</tr>
<tr>
<th>N?i dung:</th>
<td><textarea cols="30" rows="7" name="content"></textarea></td>
</tr>
</table>
<button type="submit">G?i</button>
<?php
/* Display the message from session variable and unset the variable */
if( !empty( $_GET['status'] ) && isset( $_SESSION['dbstatus'] ) ) {
$message=$_SESSION['dbstatus'];
unset( $_SESSION['dbstatus'] );
}
/* Display whatever is in $message */
echo $message;
?>
</form>
</body>
</html>

my PHP won't post to database while using w3schools example

I have been breaking my head around this html/php/mysqli thing and I can't get it to work. I used several echo statements to see what type of error I am facing but nothing shows up when I am trying to post data into my database.
I have used echo $_POST['name of input']; , print_r($_POST); and only on the 1st one I can see my post. So I think it is posting correctly, right?!
I for some strange reason can't find the problem in my code. I have searched for quiet some time on the web but with little to no result.
This is my HTML:
<html>
<head><title>Test2017</title></head>
<body>
<form action="insert.php" method="post">
<table width="400" border="0" cellspacing="10">
<tr>
<td>voornaam:</td>
<td><input type="text" name="voornaam"></td>
</tr>
<tr>
<td>roepnaam</td>
<td><input type="text" name="roepnaam"></td>
</tr>
<tr>
<td>tussenvoegsel</td>
<td><input type="text" name="tussenvoegsel"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" name="achternaam"></td>
</tr>
<tr>
<td><input type="submit" value="registreren!"></td>
</tr>
</table>
</form>
</body>
</html>
and this my insert.php, and also at the VALUES i have tried "''",'' and "" but non of that worked.
<?php
$connect=mysqli_connect("localhost","root","usbw","test");
//check connection
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
$voornaam= mysqli_real_escape_string($connect, $_POST['voornaam']);
$roepnaam= mysqli_real_escape_string($connect, $_POST['roepnaam']);
$tussenvoegsel= mysqli_real_escape_string($connect, $_POST['tussenvoegsel']);
$achternaam= mysqli_real_escape_string($connect, $_POST['achternaam']);
$sql="INSERT INTO user (voornaam,roepnaam,tussenvoegsel,achternaam) VALUES ('$voornaam','$roepnaam','$tussenvoegsel','$achternaam')";
if (!mysqli_query($connect,$sql)) {
die('Error: ' . mysqli_error($connect));
}
echo "1 record added";
mysqli_close($connect);
?>
You guys are my only help, because I am pulling my hair out for this.
Thank you in advance!
I have typed the HTML code first and I have pasted it everywhere else even in the database. So I would not have a problem like that. It is all lowercase.
I reformatted your original example to use a prepared statement, as this is safer for handling user generated input. I added a try catch around your code to attempt to raise visibility on whatever error you are running into
<?php
// ensure reporting for mysql is on.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
// Subbing out what you had for db connection to illustrate what each
// of those parameters should point to on your local db
$database = new mysqli('host', 'user', 'password', 'db_schema');
// guessing on whether these are strings.
$voornaam = filter_input(INPUT_POST, 'voornaam', FILTER_SANITIZE_STRING);
$roepnaam = filter_input(INPUT_POST, 'roepnaam', FILTER_SANITIZE_STRING);
$tussenvoegsel = filter_input(INPUT_POST, 'tussenvoegsel', FILTER_SANITIZE_STRING);
$achternaam = filter_input(INPUT_POST, 'achternaam', FILTER_SANITIZE_STRING);
// Formatting for readability, parameterized query
$query = "INSERT INTO user (
voornaam,
roepnaam,
tussenvoegsel,
achternaam
) VALUES ( ?, ?, ?, ?)";
// prepare query statement
$stmt = $database->prepare($query);
// bind parameters and types to statement
$stmt->bind_param('ssss', $voornaam, $roepnaam, $tussenvoegsel, $achternaam);
// execute
$stmt->execute();
echo 'Records added: ' . $stmt->affected_rows;
$stmt->close();
$database->close();
} catch (Exception $e) {
// basic print error to screen error handling, not ideal for
// anything other than testing :)
echo $e->getCode() . ' - ' . $e->getMessage();
}
Ok, we have probably totally confused you now, so try this
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$connect=mysqli_connect("localhost","root","usbw","test");
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
// using 4 ? one for each column value in the query
$sql="INSERT INTO user
(voornaam,roepnaam,tussenvoegsel,achternaam)
VALUES (?,?,?,?)";
$stmt = $connect->prepare($sql);
// pass the actual data for each parameter, in order
// the 'ssss' in this case denotes that all 4 params are strings
// they can be s=string, i=integer,b=blob, d=decimal
$stmt->bind_param('ssss',
$_POST['voornaam'],
$_POST['roepnaam'],
$_POST['tussenvoegsel'],
$_POST['achternaam']
);
$result = $stmt->execute();
if ( $result ) {
echo "1 record added";
} else {
echo $connect->error;
}
}
?>

Keeping a php variable that is retrieved via _GET when page reloads

I have a page that is the result of a php query click (individual job list). I want to use an ORDER BY so the individuals can order their results based on either due date, job name, etc.
The problem seems to come into play when the user clicks on the variable table header. This causes a page refresh and the variable from the _GET is obviously then gone. I tried setting it as a cookie but I believe perhaps I am not setting this correctly.
This is in the top of the document:
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['assignee'] ) ){
$assignee = filter_input( INPUT_GET, 'assignee', FILTER_SANITIZE_STRING );
}
$assignee_name = $assignee;
setcookie($assignee_name, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
This is the PHP directly before the foreach loop:
<?php
$servername = "localhost";
$username = "jobs_usr1";
$password = "xxxxxxxxx";
$dbname = "jobs_users";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `jobs_canjobs` WHERE assignee = \"$assignee\"";
$orderBy = array('job_numb', 'job_name', 'due_date', 'show_date', 'status');
$order = 'type';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
if(isset($_COOKIE[$assignee_name])){
$sql = "SELECT * FROM `jobs_canjobs` WHERE assignee = \"$assignee_name\" ORDER BY $order";
}
$results = mysqli_query($conn, $sql);
?>
Then in the results table, under the table heads, I have this:
<table>
<tr style="background-color: cadetblue">
<th><b>Job ID#</b></th>
<th><b>Title</b></th>
<th><b>Due Date</b> | <b>Show Date</b></th>
<th><b>Status</b></th>
</tr>
<?php
foreach ($results as $result){
$job_numb = $result['job_numb'];
$assignee = $result['assignee'];
$job_name = $result['job_name'];
$due_date = $result['due_date'];
$show_date = $result['show_date'];
$status = $result['status'];
?>
<tr>
<td>
<p><?php echo $job_numb;?></p>
</td>
<td>
<p><?php echo $job_name;?></p>
</td>
<td>
<p><?php echo $due_date;?> | <?php echo $show_date;?></p>
</td>
<td>
<p><?php echo $status;?></p>
</td>
</tr>
<? php } ?>
</table>
Without the reordering $order, it works just fine - but once someone clicks on the th with the order by, the variable disappears, and I am not sure how to keep it even after a page reload.
Is there a way to keep this variable $assigneeon the page so I can reference it again to display the results? I know it is the page refresh because the url after clicking does not contain the variable.
Any help would be appreciated. Thank you.
The cool thing about PHP is you can just plonk it just about anywhere within HTML document
<th><a href="?orderBy=job_numb<?php if ( (isset($_GET['assignee'])) && (!empty($_GET['assignee'])) ){
echo '&assignee='.URL_ENCODE($_GET['assignee']);}?>"><b>Job ID#</b></a></th>
This first checks if that var is defined, and isn't defined as '' aka empty
then appending to your hard coded URL..
Putting that all on one line to ensure no line breaks are introduced to the URL.
So the resulting link will end with &assignee=$VAR where $VAR is the previously set $_GET['assignee']
PS while working on scripts I always add this to teh top so I can see errors without looking at log files
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

undefined index id,fname,lastname in php

<html><head>
<title>Add record to my_database/my_table</title></head>
<body>
<?php
$self = $_SERVER['PHP_SELF'];
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
?>
<form action="<?php echo( $self ); ?>" method="post">
ID: <input type="text" name="id" size="3">
First Name: <input type="text" name="fname" size="8">
Last Name: <input type="text" name="lname" size="8"><br>
<input type="submit" value="Submit">
</form>
<?php
if( $id and $fname and $lname)
{
$conn=#mysql_connect( "localhost", "root", "" ) or die( "Err:Conn" );
select the specified database
$rs = #mysql_select_db( "add_record", $conn) or die( "Err:Db" );
create the query
$sql = "insert into my_table ( id, first_name, last_name ) values ( $id, \"$fname\", \"$lname\" )";
execute query
$rs = mysql_query( $sql, $conn );
if( $rs )
{
echo( "Record added:$id $fname $lname" );
}
}
?>
</body></html>
here am getting erro as undefined index id,fname,lastname and when i enter values in this am getting db error
At first when your page load $_POST['id'] value is empty because u ve'nt posted any value in $_POST[];
if(isset($_POST['submit'])){
//all your php code here like below
$self = mysql_real_escape_string($_SERVER['PHP_SELF']);
$id = mysql_real_escape_string($_POST['id']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
}
AND
$sql = "insert into my_table ( id, first_name, last_name ) values ( '$id', '$fname', '$lname' )";
By the way what is your db error??
Those POST values will only be set when the form is POSTed. You can use isset()
$id = isset($_POST['id'])? $_POST['id'] : NULL;
Same for others.
This happens because you have no conditions on that PHP code that will prevent it from executing the first time when the form is loaded. They should only execute when the form is submitted. You can wrap that PHP with
if(isset($_POST))
{
// Your existing database code here
}

Undefined index: userid

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');
}
?>

Categories