MySQL insert error with PHP - 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);
}

Related

form updating fields that haven't been updated by user - PHP Query

I'm in need of some help with my PHP query. I'm essentially giving users the opportunity to update their own details once they have logged in. The form:
<div class="grid-2">
<p><b>UPDATE MY DETAILS</b></p>
<form action ="includes/update.inc.php" method ="post">
<label>S.Name</label>
<input name="update-surname" type="text" placeholder="Enter new surname...">
<label>Address</label>
<input name="update-houseno" type="text" placeholder="Enter house no' or name...">
<input name="update-ln1" type="text" placeholder="1st Line of Address...">
<input name="update-town" type="text" placeholder="Town...">
<input name="update-county" type="text" placeholder="County...">
<input name="update-postcode" type="text" placeholder="Postcode...">
<label>Contact Number</label>
<input name="update-number" type="text" placeholder="Contact Number...">
<label>Email</label>
<input name="update-email" type="text" placeholder="Email...">
<input type="submit" name="update-details" value="Update">
</form>
</div>
My php code which I have currently, if the user doesn't enter anything in the box, it updates the database with a blank input (which I don't want to happen), if there's no input I don't want that field in the table touched.
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$query = "UPDATE `tblMember` SET `fldSName` = '$surname', `fldTelNum` = '$number', `fld1stLnAddress` = '$houseno', `fld2ndLnAddress` = '$ln1', `fld3rdLnAddress` = '$town', `fldCounty` = '$county', `fldPostcode` = '$postcode', `fldEmailAddress` = '$email' WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query) or die ("error");
}
?>
Once the php form is loaded, the web page disappears and doesn't stay on the current webpage their on either.
So 2 things needed, help with the correct query and help with the page going blank and not staying on the webpage.
Please note that I know this is vulnerable to injection attack I'm just trying to get it physically working before I attempt to get my head around how I do prepared statements.
Thanks!
You need to check if data input field is non-empty/valid.
Steps to avoid blank fields update:
1) Take an empty array
2) Check if every posted variable is valid, if it valid append it to array.
3) Check if the array is not empty.
4) If its not empty, fire SQL.
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$ln1 = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$update = [];
if (! empty($surname)) {
$update['fldSName'] = "fldSName = '".$surname ."'";
}
if (! empty($number)) {
$update['fldTelNum'] = "fldTelNum='".$number ."'";
}
if (! empty($houseno)) {
$update['fld1stLnAddress'] = "fld1stLnAddress='".$houseno ."'";
}
if (! empty($ln1)) {
$update['fld2ndLnAddress'] = "fld2ndLnAddress='".$ln1 ."'";
}
if (! empty($town)) {
$update['fld3rdLnAddress'] = "fld3rdLnAddress='".$town ."'";
}
if (! empty($county)) {
$update['fldCounty'] = "fldCounty='".$county ."'";
}
if (! empty($postcode)) {
$update['fldPostcode'] = "fldPostcode='".$postcode ."'";
}
if (! empty($email)) {
$update['fldEmailAddress'] = "fldEmailAddress='".$email ."'";
}
if (! empty($update)) {
$query = "UPDATE `tblMember` SET ";
$query .= implode(', ', $update);
$query .= " WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query) or die ("error");
}
}
?>
NOTE:
fldMemberID seems to be hard-coded.
For first concern you can edit your query as
UPDATE tblMember
SET fldSName = IF('$surname' = '', fldSName, '$surname'),
fldTelNum = IF('$number' = '', fldTelNum, '$number'),
fld1stLnAddress = IF('$houseno' = '', fld1stLnAddress, '$houseno'),
fld2ndLnAddress = IF('$ln1' = '', fld2ndLnAddress, '$ln1'),
fld3rdLnAddress = IF('$town' = '', fld3rdLnAddress, '$town'),
fldCounty = IF('$county' = '', fldCounty, '$county'),
fldPostcode = IF('$postcode' = '', fldPostcode, '$postcode'),
fldEmailAddress = IF('$email' = '', fldEmailAddress, '$email'),
WHERE
`tblMember`.`fldMemberID` = 1
For Second concern you have to remove die() and redirect to after-login.php as
$conn->query($query);
header("Location: ../after-login.php");
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$query = "UPDATE `tblMember` SET ";
(!empty($surname))?: $query .= "`fldSName` = '$surname',";
(!empty($houseno))?: $query .= "`fldTelNum` = '$houseno',";
(!empty($ln1))?: $query .= "`fld1stLnAddress` = '$ln1',";
(!empty($town))?: $query .= "`fld2ndLnAddress` = '$town',";
(!empty($county))?: $query .= "`fld3rdLnAddress` = '$county',";
(!empty($postcode))?: $query .= "`fldCounty` = '$postcode',";
(!empty($email))?: $query .= "`fldPostcode` = '$email',";
(!empty($number))?: $query .= "`fldEmailAddress` = '$number'";
$query .= " WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query);
header("Location: ../after-login.php"); //make sure of the path
}
Basically you are checking your input values and like that you build your query by concatenating the query blocks.
At the end added the header to redirect you to the page you want.

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

Login Page Not Connected to Registration page

the registration form is connected to the database via db.php but I am having trouble in submitting the login details.
<html>
<head>
<?php
include('db.php');
$username = #$_POST['username'];
$password = #$_POST['password'];
$submit = #$_POST['submit'];
the main problem is after the submit button is clicked by an existing user it should give the message but there's problem in the if statement, because on the wamp server its showing only the else message i.e. Error.
if ($submit)
{
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
if (mysql_num_rows($result)) {
$check_rows = mysql_fetch_array($result);
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
echo "<center>";
echo "You are now Logged In. ";
echo "</center>";
}
else {
echo "<center>";
echo "No User found. ";
echo "</center>";
}
}
else echo "Error";
?>
</head>
<body>
<form method="post">
Username : <input name="username" placeholder="Enter Username" type="text"><br></br>
Password : <input name="password" placeholder="Enter Password" type="password"><br>
<input type="submit" value="Submit">
</body>
</html>
You want get $_POST with name submit, but do not send it to the form
Try change
<input type="submit" value="Submit">
to
<input type="submit" name="submit" value="Submit">
Firstly this is old style of php/mysql. So look at PDO on php.net seeing as you are setting out on new project it really wont be hard to make the change now rather than later.
Now onto your issue. if you intend on carrying on with your old method try this.
$sql = "SELECT * FROM user WHERE username=' . $username . ' AND password=' . $password . '";
// check the query with the die & mysql_error functions
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
// checking here equal to 1 In a live case, for testing you could use >= but not much point.
if ($result == 1) {
// Checking needs to be Assoc Now you can use the field names,
// otherwise $check_rows[0], $check_rows[1] etc etc
$check_rows = mysql_fetch_assoc($query); // oops we all make mistakes, query not result, sorry.
// This is bad but for example il let this by,
// please dont access user supplied data without
// validating/sanitising it.
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
} else {
// do not logged in here
}
The same in PDO
$sql=" Your query here ";
$pdo->query($sql);
$pdo->execute();
$result = $pdo->fetch();
if ($result = 1) {
// do login stuff
} else {
// no login
}
Remember though that you need to set up PDO and it may not be available on your server by default (older php/mysql versions) but your host should be happy enough to set them up.

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
}

php form not writing form data into mysql database

I have to code below - updated
php code
if(empty($_POST['formEmail']))
{
$errorMessage .= "<li>You forgot to enter your email</li>";
}
$varEmail = $_POST['formEmail'];
if(empty($errorMessage))
{
$db = mysql_connect("servername","username","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
mysql_query($sql);
echo "Details added";
$_SESSION['status'] = 'success';
}
exit();
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
form code
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
<label for='formEmail'>Sign up to be notified when we go live!</label><br/>
<input type="text" name="formEmail" maxlength="50" value="<?=$varEmail;?>" />
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
I'm not getting any errors and as far as I can tell the syntax looks fine but its not putting the email information into the database. Anyone have an idea of whats going on? As a side note I am a newb to all php.
You've forgotten to run the query! Put
mysql_query($sql);
straight after
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
Make sure you run the $_POST variable through mysql_real_escape_string as well:
$varEmail = mysql_real_escape_string($_POST['formEmail']);
This will help protect you from SQL Injection attacks.
EDIT
One more tiny thing, I guess you want to set the session variable success when the form has submitted successfully. to do that you'll need to move
echo "Details added";
$_SESSION['status'] = 'success';
within the same if structure as the SQL query is run, otherwise it will never be set
Try:
$db = mysql_connect("servername","username","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = sprintf("INSERT INTO emails(email) VALUES ('%s')",mysql_real_escape_string($varEmail));
$results = mysql_query($sql);

Categories