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');
}
?>
Related
Can I please have some help with a problem I'm having updating a mysql database with PHP.
I'm sorry to ask a question that has been asked a lot of times before, it's just driving me a bit nuts, and I've looked through similar questions but the answers don't seem to help with my problem.
I'm using two files, an admin page (admin.php) to edit content with, and an update file that is meant to update the database when the submit button is pressed.
Everything seems to be working fine, the values are being posted to the update.php page (I can see them when I echo them out) but it wont update the database.
If anyone can please point me in the right direction or tell me what I'm doing wrong I'd be very grateful!
Thank you very much:)
This is my admin.php page;
<head>
<?php
/*
Check to see if the page id has been set in the url.
If it has, set it as the $pageid variable,
If it hasn't, set the $pageid variable to 1 (Home page)
*/
if (isset($_GET['pageid'])) {
$pageid = $_GET['pageid'];
}
else {
$pageid = '1';
}
//Database connection variables
$servername = "localhost";
$username = "root";
$password = "";
$database = "cms";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Get information from the database
$sql = "SELECT title, sub_title, tab1, tab2, tab3, content FROM data WHERE id='$pageid'";
$result = $conn ->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$conn->close();
//Store database information in variables to display in the form
$title = $row["title"];
$sub_title = $row["sub_title"];
$tab1 = $row["tab1"];
$tab2 = $row["tab2"];
$tab3 = $row["tab3"];
$content = $row["content"];
}
} else {
echo "0 results";
}
?>
</head>
<body>
//basic navigation
Page 1 | Page 2 | Page 3
<form action="update.php" method="post" name="adminform">
<input type="hidden" name="pageid" value="<?php echo "$pageid";?>">
NAME:<br>
<input type="text" name="title" value="<?php echo $title;?>"><br><br>
EMAIL:<br>
<input type="text" name="sub_title" value="<?php echo $sub_title;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab1" value="<?php echo $tab1;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab2" value="<?php echo $tab2;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab3" value="<?php echo $tab3;?>"><br><br>
CONTENT:<br>
<textarea rows="4" cols="50" name="content">
<?php echo $content;?>
</textarea>
<br><br>
<input type="submit">
</form>
</body>
And this is the update.php page;
<?php
/*Values passed from the admin form, to be used as update variables*/
if (isset($_POST['adminform']))
{
$pageid = $_POST["pageid"];
$titleu = $_POST["title"];
$sub_titleu = $_POST["sub_title"];
$tab1u = $_POST["tab1"];
$tab2u = $_POST["tab2"];
$tab3u = $_POST["tab3"];
$contentu = $_POST["content"];
}
?>
<?php
if(isset($_POST['adminform']))
{
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Update the database
$sql = "UPDATE data SET title='$titleu', sub_title='$sub_titleu', tab1='$tab1u', tab2='$tab2u', tab3='$tab3u', content='$contentu' WHERE id =='$pageid'";
$result = $conn ->query($sql);
$conn->close();
}
?>
You're using == instead of = on the where clause.
On the other hand, don't pass user values to the query without validation and sanitization if you don't want to be vulnerable to sql injection attacks.
$sql = "UPDATE data SET title='" . $conn->real_escape_string($titleu) . "', sub_title='" . $conn->real_escape_string($sub_titleu) . "', tab1='" . $conn->real_escape_string($tab1u) . "', tab2='" . $conn->real_escape_string($tab2u) . "', tab3='" . $conn->real_escape_string($tab3u) . "', content='" . $conn->real_escape_string($contentu) . "' WHERE id = " . (int)$pageid;
This will work, but is not very elegant solution. You may use prepared statements instead, to pass the correct types and prevent sql injection.
Check your DB Connections and test whether you are connected to DB or not.
Change your query as below
$sql = "UPDATE data SET title='".$titleu."', sub_title='".$sub_titleu."', tab1='".$tab1u."', tab2='".$tab2u."', tab3='".$tab3u."', content='".$contentu."' WHERE id ='$pageid'";
I outputted the results of a MySQL table to an HTML table, I'm trying to add a Delete button to remove the user but it doesn't work.
HTML form code:
<?php
$response = $bdd->query('SELECT * FROM users');
$i = 1;
while ($datas = $response->fetch()) {
?>
<tr>
<td><?php echo $datas['first_name']; ?></td>
<td><?php echo $datas['last_name']; ?></td>
<td>
<form action="_delete.php?id=<?php echo $datas['id']; ?>" method="post">
<input type="hidden" name="name" value="<?php echo $datas['id'];?>">
<input class="btn btn-danger" type="submit" name="submit" value="X">
</form>
</td>
</tr>
And this is my _delete.php :
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'root', 'root');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
?>
<?php
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
//sends the query
mysql_query ($query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
?>
My result url is good /_delete.php?id=13 but Delete script isn't.
I have this error: Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future
Any idea?
Your messing around with GET and POST params. You defined a get param named id containing your id and a post param named name containing also your id.
But currently you are trying to access the get param with $_POST (which contains only post params).
To solve your problem, you should use $_GET['id'] or $_POST['name'].
In each way, keep in mind to protect you input from sql injections. Currently the user could pass anything else as well. A simple cast to an int, would be enough.
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
I have incoporated a few suggestions in my answer, try and see if it works.
Create a connection, then get the ID using $_GET instead of $_POST.
<?php
$con=mysqli_connect("localhost","dbuser","dbpassword","dbname");
if($con==false){
die("ERROR:Could not connect.". mysqli_connect_error());
}
else{
$id=$_GET['id']
$query = "DELETE FROM users WHERE id='$id' LIMIT 1";
//sends the query
mysql_query ($con,$query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
}
?>
I have a table displaying the content of a MySQL table. For every row I added an 'edit button' so our users can update the content.
The 'edit button' goes to a link ?edit_entry.php?sid=4 with 4 the sid of the entry.
This works but I get a blank form.
Question 1: Is there any way to already display the content of the specific MySQL row in the text fields of the form?
Here is the edit_entry.php code:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
// Create connection
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = $_GET['sid'];
$sql = "SELECT * FROM orders WHERE sid = '$sid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($sql)) {
$sid = $row['sid'];
$q1_requested_by = $row['q1_requested_by'];
$q2_productname = $row['q2_productname'];
$q3_supplier = $row['q3_supplier'];
$q4_productnumber = $row['q4_productnumber'];
$q5_quantity = $row['q5_quantity'];
$q6_price = $row['q6_price'];
$q7_budget = $row['q7_budget'];
$q8_link = $row['q8_link'];
}
?>
<form action="update_script.php" method="post">
<input type="hidden" name="sid" value="<?=$sid;?>">
Requested by: <input id="q1" type="text" style="width:400px" name="ud_q1_requested_by" value="<?=$q1_requested_by?>" required="true" tabindex="1"><br>
Product name: <input id="q2" type="text" style="width:400px" name="ud_q2_productname" value="<?=$q2_productname?>" required="true" tabindex="2"><br>
Supplier: <input id="q3" type="text" style="width:400px" name="ud_q3_supplier" value="<?=$q3_supplier?>" required="true" tabindex="3"><br>
Product number: <input id="q4" type="text" style="width:400px" name="ud_q4_productnumber" value="<?=$q4_productnumber?>" required="true" tabindex="4"><br>
Quantity: <input id="q5" type="text" style="width:400px" name="ud_q5_quantity" value="<?=$q5_quantity?>" required="true" tabindex="5"><br>
Price: <input id="q6" type="text" style="width:400px" name="ud_q6_price" value="<?=$q6_price?>" tabindex="6"><br>
Budget: <input id="q7" type="text" style="width:400px" name="ud_q7_budget" value="<?=$q7_budget?>" tabindex="7"><br>
Link: <input id="q8" type="text" style="width:400px" name="ud_q8_link" value="<?=$q8_link?>" tabindex="8"><br>
<input type="submit" name="submit" id="submit" value="Update your input!" tabindex="9" />
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
And here is update_script.php:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
// Create connection
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = $_POST["sid"];
$ud_q1_requested_by = mysqli_real_escape_string($_POST["ud_q1_requested_by"]);
$ud_q2_productname = mysqli_real_escape_string($_POST["ud_q2_productname"]);
$ud_q3_supplier = mysqli_real_escape_string($_POST["ud_q3_supplier"]);
$ud_q4_productnumber = mysqli_real_escape_string($_POST["ud_q4_productnumber"]);
$ud_q5_quantity = mysqli_real_escape_string($_POST["ud_q5_quantity"]);
$ud_q6_price = mysqli_real_escape_string($_POST["ud_q6_price"]);
$ud_q7_budget = mysqli_real_escape_string($_POST["ud_q7_budget"]);
$ud_q8_link = mysqli_real_escape_string($_POST["ud_q8_link"]);
$sql= "UPDATE orders
SET q1_requested_by = '$ud_q1_requested_by', q2_productname = '$ud_q2_productname', ud_q3_supplier = '$ud_q3_supplier', ud_q4_productnumber = '$ud_q4_productnumber', ud_q5_quantity = '$ud_q5_quantity', ud_q6_price = '$ud_q6_price', ud_q7_budget = '$ud_q7_budget', ud_q8_link = '$ud_q8_link'
WHERE sid='$sid'";
$result = $conn->query($sql);
if(mysqli_affected_rows()>=1){
echo "<p>($sid) Record Updated<p>";
}else{
echo "<p>($sid) Not Updated<p>";
}
?>
There must be a problem in this last part because I get the (4) Not updated message.
Question 2: Does anyone see the problem here?
I've been trying a few things to tackle the problem but neither are working.
Thank you
mysqli_real_escape method requires the connection to be provided; this was not the case in deprecated mysqli_* methods..
see documentation at http://php.net/manual/en/mysqli.real-escape-string.php
In your case, since you are using object of mysqli:
$conn->real_escape_string($string)
Also for the record, you have a possible inject despite your attempts not to.
You should update $sid = $_POST["sid"]; to $sid = (int) $_POST["sid"]; if it is supposed to be an integer or escape it as well.
With this many variables needing to be escaped though, you should probably look at how to conduct a prepared statement. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You use mysqli, not mysql that is good news.
But you continue to use old techniques to pass parameter to query.
So let just try to bind parameters as it should be done with mysqli:
$sql= "UPDATE orders
SET
q1_requested_by = ? ,
q2_productname = ?,
ud_q3_supplier = ?,
ud_q4_productnumber = ?,
ud_q5_quantity = ?,
ud_q6_price = ?,
ud_q7_budget = ?,
ud_q8_link = ?
WHERE sid=? ";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ssssiddsi', $ud_q1_requested_by, $ud_q2_productname, $ud_q3_supplier, $ud_q4_productnumber, $ud_q5_quantity, $ud_q6_price, $ud_q7_budget, $ud_q8_link, $sid);
$result = $stmt->execute();
if($result && $stmt->affected_rows>0){
echo "<p>($sid) Record Updated<p>";
}else{
echo "Error:\n";
print_r($stmt->error_list);
echo "<p>($sid) Not Updated<p>";
}
I got it to work using the following code:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = (int)$_POST["sid"];
$ud_q1_requested_by = $conn->real_escape_string($_POST["ud_q1_requested_by"]);
$ud_q2_productname = $conn->real_escape_string($_POST["ud_q2_productname"]);
$ud_q3_supplier = $conn->real_escape_string($_POST["ud_q3_supplier"]);
$ud_q4_productnumber = $conn->real_escape_string($_POST["ud_q4_productnumber"]);
$ud_q5_quantity = $conn->real_escape_string($_POST["ud_q5_quantity"]);
$ud_q6_price = $conn->real_escape_string($_POST["ud_q6_price"]);
$ud_q7_budget = $conn->real_escape_string($_POST["ud_q7_budget"]);
$ud_q8_link = $conn->real_escape_string($_POST["ud_q8_link"]);
$sql= "UPDATE orders
SET
q1_requested_by = '$ud_q1_requested_by',
q2_productname = '$ud_q2_productname',
q3_supplier = '$ud_q3_supplier',
q4_productnumber = '$ud_q4_productnumber',
q5_quantity = '$ud_q5_quantity',
q6_price = '$ud_q6_price',
q7_budget = '$ud_q7_budget',
q8_link = '$ud_q8_link'
WHERE sid='$sid'";
$result = $conn->query($sql);
header("Location: edit_orders.php");
?>
which is just simple query, as the original form to enter a new row of data also does. I also decided to remove the error handling at the end since it didn't seem to work with mysqli_affected_rows()>0...
It's probably not a very elegant solution, but it works. Still I'd like to learn more so if anybody would have a useful link explaining php+mysqli basics that would help me much. The links to php.net or mysql.com are for me too brief at this moment though, for me they don't explain what is going on. I'm a total novice to php and mysql and could use some more explanatory/introductary text, maybe with examples, but mostly providing me with an overview of what is going on... Thanks anyway for all the help!
I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php
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);