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);
Related
Hello I am trying to use phpmyadmin and connect to my database. I did once before but I have never applied styles to the text boxes so I don't know if its right. For some reason I get an error message I told it to say if it fails to connect. I can't figure out why its not connecting. I'm using MAMP server Port: PHP 5.6.21
Here is my PHP code:
<?php
if($_POST['formSubmit'] == "Submit") {
$errorMessage = "";
if(empty($_POST['formName'])) {
$errorMessage .= "<li>You need to enter your name</li>";
}
if(empty($_POST['formEmail'])) {
$errorMessage .= "<li>You need to enter your email</li>";
}
if(empty($_POST['formSubject'])) {
$errorMessage .= "<li>Please enter a subject.</li>";
}
if(empty($_POST['formComment'])) {
$errorMessage .= "<li>Please enter your question.</li>";
}
$varname = $_POST['formName'];
$varemail = $_POST['formEmail'];
$varsubject = $_POST['formSubject'];
$varcomment = $_POST['formComment'];
if(empty($errorMessage)) {
$db = mysql_connect("localhost","root","root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("three_cats_database" ,$db);
$sql = "INSERT INTO contact_form (name, email, subject, comment) VALUES (".
PrepSQL($varname) . ", " .
PrepSQL($varemail) . ", " .
PrepSQL($varsubject) . "," .
PrepSQL($varcomment) . ") ";
mysql_query($sql);
header("Location: thankyou.php");
exit();
}
}
// function: PrepSQL()
// use stripslashes and mysql_real_escape_string PHP functions
// to sanitize a string for use in an SQL query
//
// also puts single quotes around the string
//
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
Here is my HTML:
<p>Please fill out this form completely to contact us with any concerns or suggestions.</p><br>
<div class="imgbg"><div class="img">
<!-- FORM IS HERE -->
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<div class="contact-form margin-top">
<label for='formName'><span>Name:</span>
<input type="text" class="input_text" name="formName" id="name" maxlength="50" value="<?=$varname;?>"/>
</label>
<label for='formEmail'><span>Email:</span>
<input type="text" class="input_text" name="formEmail" id="email" maxlength="50" value="<?=$varemail;?>"/>
</label>
<label for='formSubject'><span>Subject:</span>
<input type="text" class="input_text" name="formSubject" id="subject" maxlength="50" value="<?=$varsubject;?>"/>
</label>
<label><span>Comment</span>
<textarea class="message" name="formComment" id="feedback"><?php echo htmlspecialchars($varcomment);?></textarea>
</label>
<input type="submit" class="button" name="formSubmit" value="Submit" />
</label>
</div>
</form>
And last a picture of my database setup for proof of names
Here is the code that you are having a problem with. Hope this helps. I made comments explaining what was happening throughout the code so if you want to go ahead and read them, that would make you understand a tad bit better. Hope this helps.
if($_POST['formSubmit'] == "Submit") {
$errorMessage = "";
if(empty($_POST['formName'])) {
$errorMessage .= "<li>You need to enter your name</li>";
}
if(empty($_POST['formEmail'])) {
$errorMessage .= "<li>You need to enter your email</li>";
}
if(empty($_POST['formSubject'])) {
$errorMessage .= "<li>Please enter a subject.</li>";
}
if(empty($_POST['formComment'])) {
$errorMessage .= "<li>Please enter your question.</li>";
}
$varname = $_POST['formName'];
$varemail = $_POST['formEmail'];
$varsubject = $_POST['formSubject'];
$varcomment = $_POST['formComment'];
if(empty($errorMessage)) {
try
{
// I used PDO because I prefer it over mysqli
$db = new PDO('mysql:host=localhost:3306;dbname=three_cats_database, root, root');
}
catch(PDOException $e)
{
die('Unable to connect to database');
}
// Here is the sql statement that you provided.
$sql = "INSERT INTO contact_form (name, email, subject, comment)
VALUES (?,?,?,?)";
// Prepare helps with sql injections ect. It is still not completely hacker proof.
$stmt = $db->prepare($sql);
// Each question mark (?) means they increment from 1-4 in this case.
$stmt->bindValue(1, $varname, PDO::PARAM_STR);
$stmt->bindValue(2, $varemail, PDO::PARAM_STR);
$stmt->bindValue(3, $varsubject, PDO::PARAM_STR);
$stmt->bindValue(4, $varcomment, PDO::PARAM_STR);
//If statement to check if the sql command went through.This is also good for error checking.
if($stmt->execute())
{
header("Location: thankyou.php");
}
else
{
// There was an error in the statement
}
}
}
Edit this line to get more informations on your error :
if(!$db) die("Error connecting to MySQL database.");
can become :
if(!$db) die("Error connecting to MySQL database : ".mysql_error($db));
You will see more information when crashing :)
Note : create a user for your table, it's better to never write root password in your php files
PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
Getting an error of
"Error: 1
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
Please help guys, Many thanks in advance.
Code:
<?php
include('head.php');
if(isset($_POST['submit']))
{
$userid = trim($_POST['userid']);
$email = trim($_POST['email']);
$mobile = trim($_POST['mobile']);
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>******</title>
<link href="forum-styles.css" rel="stylesheet" type="text/css">
</head>
<style type="text/css">
.txtField {
padding: 5px;
border:#fedc4d 1px solid;
border-radius:4px;
}
</style>
<body background="img/gold-and-money.jpg">
<form action="" method="post" class="basic-grey">
<h1>****** Forgot Password
<span>Please let us know your UserId, We will reset password and inform you.</span> </h1>
<label>
<span>User Id :</span>
<input type="text" name="userid" required />
</label>
<label>
<span>Mobile N. :</span>
<input type="text" name="mobile" required/>
</label>
<label>
<span>Email Id :</span>
<input type="text" name="email" required/>
</label>
<label>
<div align="right"><span> </span>
<input type="submit" class="button" value="Submit" name="submit"/>
</div>
</label>
</form>
</body>
</html>
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You've got two calls here to mysqli_query. The first time, you're making the query and assigning the return value to $sql; the second time, you're running $sql as a query.
To fix the immediate problem, do something along the lines of:
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You're assigning your query to a string, and then using that in your query. This makes debugging things easier, as you can now output your generated query to check what you're producing.
However
You're also passing user-generated data directly into an SQL query, without escaping it. This is very bad - at best, you're going to have a problem if some of the data contains apostrophes. At worst, your database will get hacked. One solution here is to use escaping, as Fred suggested, using mysqli_real_escape_string:
$userid = mysqli_real_escape_string($conn, $_POST['userid']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
I'd suggest also looking at using bound parameters and a prepared statement instead, for added extra security.
Use prepared statements, or PDO with prepared statements, they're much safer.
#andrewsi answered correct: "You're running your query twice. The first time, you're assigning the result to $sql; the second time, you're trying to run that result as a query."
#andrewsi, you r running your query twice and your your query contains variables which you have make them as literals. so code would be like this:
$sql ="INSERT INTO forgot(userid,email,mobile)VALUES ($userid,$email,$mobile)";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
I hope this will help you.
Here is a basic example. Check where you have a turn. Always keep follow the standard way of coding.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
Ankit, their are few things to take care of while coding the queries, instead of explaining them, I will try to rewrite the query:
$query = sprintf("INSERT INTO forgot('userid','email','mobile')
VALUES ('%s', '%s', '%s')"
, mysqli_real_escape_string( $con, $_POST['userid'] )
, mysqli_real_escape_string( $con, $_POST['email'] )
, mysqli_real_escape_string( $con, $_POST['mobile'] ));
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted" . mysqli_affected_rows($conn) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
if in case, userid is the integer, convert the userid to int as follows before creating the $query:
$userid = (int)$_POST['userid'];
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
It will work.
I have 2 PHP pages to delete employee data from table. For that, user inserts employee id, and press delete, to delete data from table.
Now, problem is, whenever I inserts id of one digit(2,3,8 etc), id is not deleted. However, if two digit id is inserted (12,19,99 etc), it gets deleted.
Please help me to solve where I am wrong.
Here is my code for first PHP page:
<form action="deleteemp.php" method="post" onSubmit="return confirm('Are you sure to delete?')">
Enter id to delete data<input type="text" name="EmpId" required>
<button type="submit" >Delete</button>
</form>
Here is my action PHP page,
<?php
$EmpId = $_POST['EmpId'];
$connection = mysql_connect("localhost", "root", "");
if (!$connection) {
die("Connection failed " . mysql_error());
}
$db_conn = mysql_select_db("hms", $connection);
if (!$db_conn) {
die("Connection failed " . mysql_error());
}
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
$db_result = mysql_query($query, $connection);
if ($db_result) {
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
} else {
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
echo "data not here" is incorrect. mysql_query returns boolean false on FAILURE. An empty result (no matching IDs) is NOT a failure. It's a successful query which happens to have an empty result set.
Your code should be more like
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows($result) == 0) {
die("No rows deleted");
}
And note that you are vulnerable to sql injection attacks, and using an obsolete/deprecated DB library.
Try this
$query = "DELETE FROM employee_details WHERE emp_id = '$EmpId'";
$db_result = mysql_query($query, $connection);
if ($db_result)
{
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
}
else
{
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
This seems some exceptional issue, so try typecasting before passing value to SQL query.
Try using this for assigning value to $EmpId:
$EmpId = (int) $_POST['EmpId'];
can you try to change below code from
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
TO
$query = "DELETE FROM employee_details WHERE emp_id =".$EmpId;
Just try. This might work for you
/Form design/
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name="form1" method="post" action=""><label><center>Register Form</center></label>
<p><center></center><label>Name:</label>
<input type="text" name="name"></center>
</p>
<p><label>Rollno:</label>
<input type="text" name="rno">
</p>
<p><label>Address:</label>
<input type="text" name="add">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
/***********PHP******************/
/Form submission/
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name'],$con);
$rno = mysql_real_escape_string( $_POST['rno'],$con);
$add = mysql_real_escape_string($_POST['add'],$con);
$sql=mysql_query("INSERT INTO test (name, rno, add)
VALUES ('$name','$rno','$add')",$con);
$result=mysql_query($sql) or die(mysql_error());
if (!mysql_query($result,$con)) {
die(mysql_error($con));
}
echo "1 record added";
mysql_close($con);
?>
</body>
</html>
some one please help me with this error.
i am getting the message query was empty.
how can i fix this.
i am new to php and my sql.
i dont know how to solve this issue.
mysql_query should execute a query :
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name'],$con);
$rno = mysql_real_escape_string( $_POST['rno'],$con);
$add = mysql_real_escape_string($_POST['add'],$con);
$query = sprintf("INSERT INTO test (name, rno, add)
VALUES ('%s','%s','%s')", $name, $rno, $add);
$result = mysql_query($query, $con);
if (!$result) {
$message = 'Invalid request : ' . mysql_error() . "\n";
$message .= 'Your query : ' . $query;
die($message);
}
// #see http://php.net/manual/en/function.mysql-affected-rows.php
echo mysql_affected_rows() + " record added";
mysql_close($con);
?>
Try this
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name']);
$rno = mysql_real_escape_string( $_POST['rno']);
$add = mysql_real_escape_string($_POST['add']);
$sql=mysql_query("INSERT INTO test (name, rno, add) VALUES ('$name','$rno','$add')",$con);
if ($sql) {
echo "1 record added";
}
else {
die(mysql_error($con));
}
mysql_close($con);
First of all, if you have kept your html form code and php code in the same page, you will need a conditional operator to check whether the form has been submitted or not. In your code above, the php code are executed even when the form is not submitted.
Make sure your form data are fetched by using any of the following:
var_dump($_POST);
print_r($_POST);
If it displays the data you have entered then so far you are good.
In your code above you have:
$result=mysql_query($sql) or die(mysql_error());
When you have done the above, you will not need the following code as the die() function will do the same. And the following code will also make your query run twice.
if (!mysql_query($result,$con)) {
die(mysql_error($con));
}