undefined index id,fname,lastname in php - 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
}

Related

Dynamic insert into DB

i'm creating a simple web app which a form to insert data in DB ( Postgres).
I have this tables:
prenotazione (id,nome_rich,cogn_rich,email_rich,oggetto_rich)
interni (id,nome_int,cogn_int,email_int)
esterni (id,nome_est,cogn_est,email_est)
Now about the tables "interni" and "esterni" the users should choose how many data want to insert, so i have implemented a dynamic form:
**index.php
<div id="start">
<div id="first">
Nome:<input type="text" name="iname[]" size="20"><br>
Cognome: <input type="text" name="isurname[]" size="20"><br>
Email: <input type="email" name="iemail[]" size="20"><br>
<br>
</div>
</div>
<br>
<b> Numero partecipanti interni:</b>
<input type="text" id="n1" value="1"><br>
<button>Aggiungi partecipante</button>
</div>
**input.php
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$testo = $_POST['testo'];
//inserting data order
$query1 = "INSERT INTO prenotazione (id,nome_rich, cogn_rich, email_rich,oggetto_rich) VALUES (1,'$name','$surname', '$email','$testo')";
//execute the query here
$result = pg_query($conn, $query1 ); //if you are using pg_query and $conn is the connection resource
// Interni
$query = "";
if( !empty( $_POST['iname'] ) ) {
foreach( $_POST['iname'] as $key => $iname ) {
$isurname = empty( $_POST[$key]['isurname'] ) ? NULL : $_POST[$key]['isurname'];
$iemail = empty( $_POST[$key]['iemail'] ) ? NULL : $_POST[$key]['iemail'];
$query .= " ( '$iname', '$isurname', '$iemail' ) ";
}
}
if( !empty( $query ) ) {
$query2 = "INSERT INTO interni (nome_int, cogn_int, email_int) VALUES ".$query;
$result = pg_query($conn, $query2 );
The problem is that when they try to insert data into "interni" and the data are more than one, they can't and i receive an error. ( basically the table "interni" is empty when they try to insert more than one ).
How can i solve the problem?
Thanks you all
You are missing comma in between VALUES.
This is what you are executing: INSERT INTO table VALUES (stuff) (stuff2) (stuff3)
Correct is: INSERT INTO table VALUES (stuff), (stuff2), (stuff3)
Fix:
$iemail = empty( $_POST[$key]['iemail'] ) ? NULL : $_POST[$key]['iemail'];
if($query != "") {
$query .= ",";
}
$query .= " ( '$iname', '$isurname', '$iemail' ) ";

Can't update form data

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.

PHP MySQL UPDATE statement

I am making a website where after you have logged in and added all your contacts in the database you can also edit them. The way to go is the MYSQL UPDATE statement. I have written the code but sosmething does not seem to work and has been torturing me for hours. Here is the code
<?php
session_start();
$del_id = $_GET["id"];
$_SESSION["id"] = $del_id;
$del_name = $_GET["name"];
$del_phone = $_GET["phone"];
$del_address = $_GET["address"];
$del_email = $_GET["email"];
$name2 = $_POST["name"];
$address2 = $_POST["address"];
$number2 = $_POST["number"];
$email2 = $_POST["email"];
$query = "UPDATE `contacts` SET email = '$email2' AND phone = '$number2' AND address = '$address2' AND name = '$name2' WHERE id = '$del_id'";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn){
die("Connection failed: ".mysqli_connect_error());
}else{
echo "Connected successfully";
}
if(mysqli_query($conn,$query)){
echo "Contact edited";
}
?>
<html><head></head>
<body>
<form action="edit.php" method = "POST">
Add text only to the ones you want changed:<br><br>
NAME<input type="text" value="<?php echo $del_name?>" name="name"><br>
ADDRESS<input type="text" value="<?php echo $del_address?>" name="address"><br>
PHONE NUMBER <input type="text" value="<?php echo $del_phone ?>" name="number"><br>
EMAIL <input type="text" value="<?php echo $del_email ?>" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
What could be the problem because the contact in the database is not being updated after that?
Your UPDATE statement is wrong:
"UPDATE `contacts` SET email = '$email2' AND phone = '$number2' AND address = '$address2' AND name = '$name2' WHERE id = '$del_id'"
Try this instead
// Please sanitize the data
$email2 = filter_var( $email2, FILTER_SANITIZE_EMAIL );
$name2 = preg_replace( "#[^a-zA-Z ]#", '', $name2 );
$number2 = preg_replace( "#[^0-9 \-\+]#", '', $number2 );
$address = preg_replace( "[^\w \.\-\+]#", '', $address2 );
"UPDATE `contacts` SET email = '$email2', phone = '$number2', address = '$address2', name = '$name2' WHERE id = '$del_id' LIMIT 1"
Note
I added the limit clause LIMIT 1 to limit the number of rows that will be affected by the update statement. In this case, am setting it to 1 to make sure we're updating a single row. Am sure you would want that also.
* Please, consider using mysqli prepared query or PDO
Replace your $query line.
$query = "UPDATE `contacts`
SET email = '$email2', phone = '$number2', address = '$address2', name = '$name2'
WHERE id = '$del_id'";
AND can be used in WHERE clause.
$query = "UPDATE `users` SET `userpassword` = CONCAT(`userpassword`, 'a') WHERE `user_id` = 1";
READ THE GUIDELINES

MySQL insert error with PHP

I'm having trouble with the actual insert line. Right now it just inserts a blank row in the table. Am I bringing in the $email line incorrectly (line that starts with "$sql =...")?
<script>
function validate(form_id,email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[form_id].elements[email].value;
if(reg.test(address) == false) {
alert('Invalid Email Address');
return false;
}
<?php
if (isset($_POST['email']))
{
$email = mysql_real_escape_string($_POST['email']);
mysql_connect(blah) or die(mysql_error());
mysql_select_db(blah) or die(mysql_error());
$sql = "INSERT INTO `email` (`email`) VALUES ('".$email. "')";
mysql_query($sql);
}
?>
}
</script>
<form id="form_id" method="post" action="#" onsubmit="javascript:return validate('form_id','email');">
<input type="text" id="email" name="email" />
<input type="submit" value="Submit" />
</form>
You can't call mysql_real_escape_string() until AFTER you've connected to the database. Otherwise you'll just get a warning and a boolean FALSE returned.
Change the order of the code to:
mysql_connect(blah) or die(mysql_error());
mysql_select_db(blah) or die(mysql_error());
$email = mysql_real_escape_string($_POST['email']);
This is done because the m_r_e_s() call needs to retrieve version/status information, particularly which characters need to be escaped, and this can't be done without an active DB connection.
You must call mysql_real_escape_string after mysql connect.
Try set error_reporting(E_ALL); you will see an error.
This should workif (isset($_POST['email']))
{
$email = $_POST['email'];
mysql_connect(blah) or die(mysql_error());
mysql_select_db(blah) or die(mysql_error());
$sql = sprintf("INSERT INTO email (email) VALUES ('%s')", mysql_real_escape_string($email));
mysql_query($sql);
}

Comments not Getting Inserted into MySQL Table

I'm trying to use the code below for a comment system. It doesn't work. The info I'm trying to insert into the MySQL table "comment" isn't getting put there. Any idea(s) why it is not working?
Thanks in advance,
John
On comments.php:
echo '<form action="http://www...com/sandbox/comments/comments2.php" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<label class="addacomment" for="title">Add a comment:</label>
<input class="commentsubfield" name="comment" type="title" id="comment" maxlength="1000">
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
On comments2.php:
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
mysql_query("INSERT INTO comment VALUES (NULL, '$uid', '$subid', '$comment', NULL, NULL)");
try
$query = sprintf("INSERT INTO comment VALUES (NULL, '%s', '%s', '%s', NULL, NULL)", $uid, $subid, $comment);
mysql_query($query);
If mysql_query() fails it returns false and mysql_error() can tell you why.
Also take a look at http://docs.php.net/security.database.sql-injection and either use mysql_real_escape_string() or prepared statements.
if ( !isset($_POST['comment'], $_POST['uid'], $_POST['submissionid']) ) {
echo '<pre>Debug: Something is missing. _POST=',
htmlspecialchars( print_r($_POST, 1) ),
'</pre>';
die;
}
$comment = mysql_real_escape_string($_POST['comment'], $mysql);
$uid = mysql_real_escape_string($_POST['uid'], $mysql);
$subid = mysql_real_escape_string($_POST['submissionid'], $mysql);
$query = "
INSERT INTO
comment
VALUES
(NULL, '$uid', '$subid', '$comment', NULL, NULL)
";
echo '<pre>Debug query=', htmlspecialchars($query), '</pre>';
$rc=mysql_query($query, $mysql);
if ( !$rc ) {
die( htmlspecialchars(mysql_error()) );
}
Try this self-contained example (only an example, don't code it this way ;-))
<?php
session_start();
if ( !isset($_SESSION['loginid']) ) {
login();
}
else if ( !isset($_POST['comment']) ) {
showForm();
}
else {
saveComment();
}
function saveComment() {
if ( !isset($_POST['comment'], $_POST['uid'], $_POST['submissionid']) ) {
echo '<pre>Debug: Something is missing. _POST=',
htmlspecialchars( print_r($_POST, 1) ),
'</pre>';
die;
}
// insert correct values here:
$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error());
$comment = mysql_real_escape_string($_POST['comment'], $mysql);
$uid = mysql_real_escape_string($_POST['uid'], $mysql);
$subid = mysql_real_escape_string($_POST['submissionid'], $mysql);
$query = "
INSERT INTO
comment
VALUES
(NULL, '$uid', '$subid', '$comment', NULL, NULL)
";
echo '<pre>Debug query=', htmlspecialchars($query), '</pre>';
//$rc=mysql_query($query, $mysql);
//if ( !$rc ) {
//die( htmlspecialchars(mysql_error()) );
//}
}
function login() {
$_SESSION['loginid'] = rand(1, 100);
echo 'Your new loginid is ', $_SESSION['loginid'],'<br />
Continue
';
}
function showForm() {
$submissionid = rand(1000, 9999);
echo '<div>submissionid=', $submissionid, '</div>';
echo '<div>loginid=', $_SESSION['loginid'], '</div>';
echo '<form action="?" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<label class="addacomment" for="title">Add a comment:</label>
<input class="commentsubfield" name="comment" type="title" id="comment" maxlength="1000">
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
}
if this "works" compare it to your real application and find the (essential) differences.
Valid return values from yourform
Does
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
contain valid data?
SQL query valid
http://www.w3schools.com/sql/sql_insert.asp
What does mysql_query return
<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
what mysql_error do you get for your query.
Use PDO instead of mysql_query()
I would advise you to have a look at PDO which does a lot of heavy lifting for you. It for example makes sure that your SQL query is safe because even if the comments was added to your database it could(would) not be safe at all.
PHP security
You should always validate your users input to prevent SQL injection. Luckily when using PDO(using prepared statements which will also give you a speed boost)right this will be done for you behind the seens. Still I would advise you to read these quick security tips from PHP creator to secure your site.
Hopefully this tips will help you in any way.
You need the field names for any INSERT statement. As I don't know the exact ones for your table, I'll make some guesses.
mysql_query("INSERT INTO comment(uid,subid,comment) VALUES($uid, $subid, $comment)");

Categories