unexpected error message in php form (SQL syntax error) - php

I have made a simple php cms form with database but it does not work properly when I want to submit the form with some dummy data! I don't know why it happens & also I added the mysqli_error() to get the type of error that I'm facing with but I only got this:
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 '','','')' at line 2
<?php
if (isset($_POST['submit'])){
$post_title = $_POST['title'];
$post_date = date('d-m-y');
$post_author = $_POST['author'];
$post_keywords = $_POST['keywords'];
$post_content = $_POST['content'];
$post_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
echo '<script>alert("Some fields are missing")</script>';
}else{
move_uploaded_file($image_tmp,"post_images/$post_image");
$insert_query = "INSERT INTO posts
(post_title,post_date,post_author,post_image,post_keywords,post_content) VALUES ('$post_title','$post_date','$post_author',$post_image','$post_keywords','$post_content')";
$insert_post = mysqli_query($con,$insert_query);
if ($insert_post){
echo '<h3 style="color:green">Post has been added successfully.</h3>';
}else{
echo mysqli_error($con);
}
}
}
?>
<form method="POST" action="" enctype="multipart/form-data">
<table width="600" align="center" border="10">
<tr>
<td align="center"><h6>Insert Post Title</h6></td>
<td align="center"><input type="text" name="title"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Author</h6></td>
<td align="center"><input type="text" name="author"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Keywords</h6></td>
<td align="center"><input type="text" name="keywords"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Image</h6></td>
<td align="center"><input type="file" name="image"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Content</h6></td>
<td align="center"><textarea name="content" cols="10" rows="10"></textarea></td></br>
</tr>
<tr>
<td align="center"><input type="submit" name="submit" value="Submit"/></td>
</tr>
</table>
</form>
It would be very helpful to me if you share your solution for this problem... thanks!

You are missing a quote just before $post_image:
,$post_image'
Should be:
,'$post_image'
So the complete SQL statement becomes then:
$insert_query = "INSERT INTO posts
(post_title, post_date, post_author, post_image, post_keywords, post_content)
VALUES ('$post_title', '$post_date', '$post_author', '$post_image',
'$post_keywords', '$post_content')";
Please note that you are doing assignments in this if:
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
You should be using double == instead of =.
Finally, your code is vulnerable to SQL injection. So please use prepared statements with parameters.

writing if statement in this way is better
// this not always works
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
echo '<script>alert("Some fields are missing")</script>';
}
// yeah much better
if (empty($post_title) || empty($post_keywords) || empty($post_content) || empty($post_author)){
echo '<script>alert("Some fields are missing")</script>';
}
and sql mistake most probably because of here
'$post_keywords','$post_content')";
$post_keywords and $post_content is null or empty

Changes
Use empty for check empty variable
Use || instead of or
Check validation for what you are doing. (move_uploaded_file)
Be careful with quotes ($post_image') - This is the bug in your code
Enhance mysqli_error (if (!$insert_post){)
Code
<?php
if (isset($_POST['submit']))
{
$post_title = $_POST['title'];
$post_date = date('d-m-y');
$post_author = $_POST['author'];
$post_keywords = $_POST['keywords'];
$post_content = $_POST['content'];
$post_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if (empty($post_title) || empty($post_keywords) || empty($post_content) || empty($post_author))
{
echo '<script>alert("Some fields are missing")</script>';
}
else
{
if (!move_uploaded_file($image_tmp,"post_images/$post_image")) {
echo "Move Failed";
}
else
{
$insert_query = "INSERT INTO posts (post_title,post_date,post_author,post_image,post_keywords,post_content) VALUES ('$post_title','$post_date','$post_author','$post_image','$post_keywords','$post_content')";
$insert_post = mysqli_query($con,$insert_query);
if (!$insert_post){
echo mysqli_error($con);
}
else
{
echo '<h3 style="color:green">Post has been added successfully.</h3>';
}
}
}
}
?>

Related

PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Please help not able to resolve, trying since three days but not able to know what the reason its throwing me such message. (below is my complete code).
<!DOCTYPE html>
<html>
<head>
<title>Insert New Post</title>
</head>
<body>
<form method="post" action="insert_post.php" enctype="multipart/form-data">
<table align="center" border="10" width="600">
<tr>
<td align="center" colspan="5" bgcolor="yellow"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="40"></td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author"></td>
</tr>
<tr>
<td align="right">Post image:</td>
<td><input type="file" name="image_name"></td>
</tr>
<tr>
<td align="right">Post Content:</td>
<td><textarea name="content" cols="50" rows="20"></textarea></td>
</tr>
<tr>
<td align="center" colspan="5"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
Above Form is to insert and submit data in Database
// PHP
<?php
include("includes/connect.php");
if (isset($_POST['submit'])) {
$title = $_POST['title'];
$datenow = date('Y/m/d');
$author = $_POST['author'];
$content = $_POST['content'];
$image_name = $_FILES['image_name']['name'];
$image_type = $_FILES['image_name']['type'];
$image_size = $_FILES['image_name']['size'];
$image_tmp = $_FILES['image_name']['tmp_name'];
if ($title =='' || $author =='' || $content =='') {
echo "<script>alert('Any feild is empty')</script>";
exit();
}
if ($image_type =='image/jpeg' || $image_type =='image/png' || $image_type =='image/gif') {
if ($image_size<=5000000000) {
move_uploaded_file($image_tmp, "images/$image_name");
}
else{
echo "<script>alert('Image is larger, only 50kb size is allowed') </script>";
}
}
else{
echo "<script>alert('image type is invalid')</script>";
}
// insert query
$sth = $con->prepare(" INSERT INTO posts (post_title, post_date, post_author, post_image, post_content) VALUE (:title,:datenow,:author,:image_name,:content) ");
$sth->bindParam(':post_title', $title);
$sth->bindParam(':post_date', $datenow);
$sth->bindParam(':post_author', $author);
$sth->bindParam(':post_image', $image_name);
$sth->bindParam(':post_content', $content);
$sth->execute();
echo "<h1>Form Submited Successfully</h1>";
}
?>
// $sth->execute(); is throwing error massage as above
You are binding wrong values.You haven't bind the post_* values. See below:
$sth = $con->prepare(" INSERT INTO posts (post_title, post_date, post_author, post_image, post_content) VALUES (:post_title,:post_date,:post_author,:post_image,:post_content) ");
$sth->bindParam(':post_title', $title);
$sth->bindParam(':post_date', $datenow);
$sth->bindParam(':post_author', $author);
$sth->bindParam(':post_image', $image_name);
$sth->bindParam(':post_content', $content);

Data is not posting in database

i am new to php and started developing one dynamic website, i have created few static pages and one news page.
For news page i have created database in phpmyadmin but i am not able to get any data in my database but i am getting images in images folder, please have look in my codes.
to insert post i have created this :
<html>
<head>
<title>Insert New Post</title>
</head>
<body>
<form method="post" action="insert_post.php" enctype="multipart/form-data">
<table allign="center" border="10" width="600">
<tr>
<td align="center" colspan="5" bgcolor="yellow">
<h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="40"></td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author"></td>
</tr>
<tr>
<td align="right">Post image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post content:</td>
<td><textarea name="content" cols="40" rows="20"></textarea></td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
include('includes/connect.php');
if(isset($_POST['submit'])){
$title = $_POST['title'];
$date = DATE('y-m-d');
$author = $_POST['author'];
$content = $_POST['content'];
$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp = $_FILES['image']['tmp_name'];
if($title == '' or $author =='' or $content ==''){
echo "<script>alert('Any filed is empty')</script>";
exit();
}
if($image_type=="image/jpeg" or $image_type=="image/png" or $image_type=="image/gif"){
if($image_size<=50000){
move_uploaded_file($image_tmp,"images/$image_name");
}
else {
echo "<script>alert('image is larger, only 50kb size is allowed')</script>";
}
}
else {
echo "<script>alert('image type is invalid')</script>";
}
$query = "insert into post (post_title,post_date,post_author,post_image,post_content) values ('$title','$date','$author','$image_name','$content')";
if(mysql_query($query)){
echo "<center><h1>Post has been Published</h1></center>";
}
}
?>
Now i have created connect.php files, witch have following codes:
<?php
mysql_connect("localhost","root","");
mysql_select_db("rect");
?>
i am new to php so sorry if i did anything wrong in question and thank you in advance.
Note:
Make sure you have a table named post with this corresponding column names: post_title, post_date, post_author, post_image, post_content
And as suggested by #spencer7593, I'll try to convert your code to mysqli_* as their is a problem with your connection, and also to prevent SQL injections.
If you're gonna insert date into your database, instead of:
$date=DATE("y-m-d"); /* YY-MM-DD */
you should do:
$date=DATE("Y-m-d"); /* YYYY-MM-DD */
First is we fix your connection to your database (connect.php):
<?php
$mysqli = new mysqli("localhost", "root", "", "rect");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
Then change your insert query like this simple example:
$stmt = $mysqli->prepare("INSERT INTO post (post_title, post_date, post_author, post_image, post_content) VALUES (?,?,?,?,?)");
$stmt->bind_param('sssss',$title,$date,$author,$image_name,$content); /* BIND VARIABLES TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
?>

HTML/PHP Form Not Working On Live Server

I have this code in my form:
<form id="addForm" action="php/add-article.php" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td class="tableLeft">Article Photo:</td>
<td class="tableRight"><input id="formPhoto" class="addTextInput" name="photo" type="file" /></td>
<td id="validatePhoto"></td>
</tr>
<tr>
<td class="tableLeft">Article Photo Alt:</td>
<td class="tableRight"><input id="formAlt" class="addTextInput" name="alt" type="text" /></td>
<td id="validateAlt"></td>
</tr>
<tr>
<td class="tableLeft">Article Title:</td>
<td class="tableRight"><input id="formTitle" class="addTextInput" name="title" type="text" /></td>
<td id="validateTitle"></td>
</tr>
<tr>
<td class="tableLeft">Article Body:</td>
<td class="tableRight"><textarea id="formArticle" class="addTextInput" rows="6" name="article"></textarea></td>
<td id="validateArticle"></td>
</tr>
<tr>
<td class="tableLeft"></td>
<td id="validateSending" class="tableRight"></td>
</tr>
<tr>
<td class="tableLeft"></td>
<td class="tableRight"><input id="formSubmit" class="addSubmitInput" type="submit" value="Add This" /></td>
</tr>
</table>
</form>
And this in a php file (add-article.php):
<?php
$time = time();
$id= time().''.mt_rand(1000, 9999);
$year = date("Y");
$path = "../images/$year/";
$title = ucwords($_POST['title']);
$article = $_POST['article'];
$alt = $_POST['alt'];
$extension = end(explode(".", $_FILES["photo"]["name"]));
$added = date("Y-m-d H:i:s");
$views = "0";
?>
<?php
$insert_post_sql = "INSERT INTO articles (id, photo, alt, title, article, added, views) VALUES('$id', '.$extension', '$alt', '$title', '$article', '$added', '$views')";
$insert_post_res = mysqli_query($con, $insert_post_sql);
if(mysqli_affected_rows($con)>0){
move_uploaded_file($_FILES["photo"]["tmp_name"],"$path" . $id . "." . $extension);
header("Location: ../article.php?id=$id");
exit();
}
else{
echo "0";
};
?>
When I run this on my localhost, everything works compltely fine yet when I do it on my live site it echo's 0 and says that photo, alt, title and article are uindefined.
Does anyone know what the reason for this might be?
The main reason should be the move_uploaded_file permission to write in the specified path on the production server.
The problem is from your sql statement... it couldnt find the photo, alt etc... on the table header that is why it returned 0 records, hence, echoing 0 as your program demands....
I edited the last <tr> of your form
<tr>
<td class="tableLeft"></td>
<td class="tableRight"><button id="formSubmit" class="addSubmitInput" type="submit" name="submit">Add This </button></td>
</tr>
Now try below PHP code:
<?php
$time = time();
$id = time() . '' . mt_rand(1000, 9999);
$year = date("Y");
$path = "../images/$year/";
if (isset($_POST['submit'])) {
$title = ucwords($_POST['title']);
$article = $_POST['article'];
$alt = $_POST['alt'];
$extension = end(explode(".", $_FILES["photo"]["name"]));
$added = date("Y-m-d H:i:s");
$views = "0";
$insert_post_sql = "INSERT INTO articles (id, photo, alt, title, article, added, views) VALUES('$id', '.$extension', '$alt', '$title', '$article', '$added', '$views')";
$insert_post_res = mysqli_query($con, $insert_post_sql);
if (mysqli_affected_rows($con) > 0) {
move_uploaded_file($_FILES["photo"]["tmp_name"], "$path" . $id . "." . $extension);
header("Location: ../article.php?id=$id");
exit();
} else {
echo "0";
};
}
?>
Let me know if its working for you now. Regards.

php stop of statement in form validation

i am a beginner and am trying to make a form validation with PHP. i want to check if one of the inputs is empty, the form says that the empty input is required.
I show the php script behind.
<?php
$titleErr = $authorErr = $keywordsErr = $contentErr = "";
$title = $author = $keywords = $content = "";
if (empty($_POST["submit"])) {
if(empty($_POST["title"])){
$titleErr = "title is required";
}
if(empty($_POST["author"])){
$authorErr = "author name is required";
}
if(empty($_POST["keywords"])){
$keywordsErr = "keywords are required";
}
if(empty($_POST["content"])){
$contentErr = "This field is required";
}
}
?>
<form method="post" action="insert_post.php">
<table width="600" align="center" border="10">
<tr>
<td align="center" bgcolor="yellow" colspan="6"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="38">
<span style="color:red;"><?php echo $titleErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author" size="38">
<span style="color:red;"><?php echo $authorErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords" size="38">
<span style="color:red;"><?php echo $keywordsErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content</td>
<td><textarea name="content" cols="30" rows="15"></textarea>
<span style="color:red;"><?php echo $contentErr; ?></span>
</td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
include("includes/connect.php");
if(isset($_POST['submit'])){
$title = $_POST['title'];
$date = date('d-m-Y');
$author = $_POST['author'];
$keywords = $_POST['keywords'];
$content = $_POST['content'];
$image = $_FILES['image'] ['name'];
$image_tmp = $_FILES['image'] ['tmp_name'];
move_uploaded_file($image_tmp, "../images/$image");
$query = "INSERT INTO posts (post_title, post_date, post_author, post_keywords, post_image, post_content) VALUES('$title', '$date', '$author', '$keywords', '$image', '$content')";
$result = mysqli_query($conn, $query);
if($query){
echo"<center><h1>Post Published Succesfully!</h1></center>";
}
}
?>
The problem is i want to stop the scrit if the inputs are empty but i can't use functions like: exit() and break;.
and if i submit, the form sends empty values to the database :C.
how can i solve this problem?
We make use of session variables which temporarily stores data locally. To use sessions we must always start sessions by session_start() at the start of every page to be able to access the variables. Now we can store data and pass it to whatever page we want to without having to send it - we just store it and then grab it.
index.php
<?php
session_start();
$titleErr = $authorErr = $keywordsErr = $contentErr = "";
$title = $author = $keywords = $content = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["title"])){
$titleErr = "title is required";
}
if(empty($_POST["author"])){
$authorErr = "author name is required";
}
if(empty($_POST["keywords"])){
$keywordsErr = "keywords are required";
}
if(empty($_POST["content"])){
$contentErr = "This field is required";
}
if(!empty($_POST["title"]) && !empty($_POST["author"]) && !empty($_POST["keywords"]) && !empty($_POST["content"])){
$_SESSION["title"] = $_POST["title"];
$_SESSION["author"] = $_POST["author"];
$_SESSION["keywords"] = $_POST["keywords"];
$_SESSION["content"] = $_POST["content"];
$_SESSION["image"] = $_FILES["image"];
header("location: insert_post.php");
exit();
}
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="600" align="center" border="10">
<tr>
<td align="center" bgcolor="yellow" colspan="6"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="38" value="<?php if(isset($_POST['title'])){ echo $_POST['title']; }; ?>">
<span style="color:red;"><?php echo $titleErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author" size="38" value="<?php if(isset($_POST['author'])){echo $_POST['author']; }; ?>">
<span style="color:red;"><?php echo $authorErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords" size="38" value="<?php if(isset($_POST['keywords'])){echo $_POST['keywords']; }; ?>">
<span style="color:red;"><?php echo $keywordsErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content</td>
<td><textarea name="content" cols="30" rows="15" value="<?php if(isset($_POST['content'])){echo $_POST['content']; }; ?>"></textarea>
<span style="color:red;"><?php echo $contentErr; ?></span>
</td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
insert_post.php
<?php
session_start();
include("includes/connect.php");
$title = $_SESSION['title'];
$author = $_SESSION['author'];
$keywords = $_SESSION['keywords'];
$content = $_SESSION['content'];
$date = date('d-m-Y');
$image = $_SESSION['image']['name'];
$image_tmp = $_SESSION['image']['tmp_name'];
move_uploaded_file($image_tmp, "../images/$image");
$query = "INSERT INTO posts (post_title, post_date, post_author, post_keywords, post_image, post_content) VALUES('$title', '$date', '$author', '$keywords', '$image', '$content')";
$result = mysqli_query($conn, $query);
if($query){
echo"<center><h1>Post Published Succesfully!</h1></center>";
}
else{
echo "<center><h1>Error! Post was not published!</h1></center>";
}
echo $title . " " . $author . " " . $keywords . " " . $content;
?>
Btw, you should be using prepared statements for your database inserts to prevent SQL-injections. Read more about it here.
You don't hAve to Break the Script using the Exit Funktion. Just prove if the error variables aren't empty and only in the Case when they aren't empty send a dB-request.
Chenge these lines:
include("includes/connect.php");
if(isset($_POST['submit'])){
to
include("includes/connect.php");
if( isset($_POST['submit']) //Fix here, it will only insert if all error message
&& empty($titleErr) //are empty.
&& empty($authorErr)
&& empty($keywordsErr)
&& empty($contentErr) ){
Edit
And also change this line
if (empty($_POST["submit"])) {
To
if (isset($_POST["submit"])) {
On the init of your script. The empty function will return true if you did not submit the page, that's why you are hving the error messages.

php validation code format

Okay I have this MySQL database form and am trying to add validation to it. After 2 days of fighting with it, I thought I would get some advice. Would like that the selected item from dropdown and Firstname, Phone, Email, are all required. Then I want to verify that the data in the Firstname, Lastname, Phone (doesn't have to be any special format), Email and Comments are all acceptable formats before putting in database. Here is what I have so far:
<?php
include('inc_header.php');
if(isset($_POST['add']))
{
require('dbcon.php');
if(! get_magic_quotes_gpc() )
{
$Id = addslashes ($_POST['Id']);
$List = addslashes ($_POST['List']);
$Firstname = addslashes ($_POST['Firstname']);
$Lastname = addslashes ($_POST['Lastname']);
$Phone = addslashes ($_POST['Phone']);
$Email= addslashes ($_POST['Email']);
$Calltime = addslashes ($_POST['Calltime']);
$Comment = addslashes ($_POST['Comment']);
}
else
{
$Id = $_POST['Id'];
$Date = $_POST['Date'];
$List = $_POST['List'];
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Phone = $_POST['Phone'];
$Email = $_POST['Email'];
$Calltime = $_POST['Calltime'];
$Comment = $_POST['Comment'];
}
$error = '';
//put chosen function here
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function isValidEmail( $Email ){
return filter_var( $Email, FILTER_VALIDATE_EMAIL );
}
//get values and validate each one as required
$List = mysql_real_escape_string($_POST['List']);
if(!$List){ $error .= "Please choose one<br />"; }
$Firstname = mysql_real_escape_string($_POST['Firstname']);
if(!$Firstname){ $error .= "First name is required<br />"; }
//get values and validate each one as required
$Lastname = mysql_real_escape_string($_POST['Lastname']);
if(!$Lastname){ $error .= "Last name is required<br />"; }
//repeat for each field
$Email = mysql_real_escape_string($_POST['Email']);
if(!isValidEmail($Email)){ $error .= "The email entered is invalid<br />"; }
//and so on...
if(!$error){
//add insert into database code here
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<? print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><? print(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>
</body>
</html>
So far I just keep chasing error message. Please forgive formatting I am trying to learn be gentle.
Your query arguments are backwards, and you should be using mysqli_. Here is the correct order.
$retval = mysqli_query($conn, $sql);
mysqli_query documentation
you need an end bracket for this statement: (if(!$error){)
edit: the } you were missing is actually a closing bracket for if(isset($_POST['add'])), not magic quotes. sorry!
//and so on...
if(!$error)
{
//add insert into database code here
// this probably won't run right...
// you're missing a ( after the word values...
// insert into tablename (id, name, stuff) values (1,'gloomy','stuff);
// this part of your statement is not correct: "VALUES'$Id,','$Date',
// and the commas are off, too.
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
// print your SQL here to make sure it is correct.
// copy and paste it to run it directly in the DB. if it won't run there
// it won't run here
print $sql."<br/>";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
} // <-------- you're missing this closing bracket
} // this ends the statement for if(isset($_POST['add'])) { ....
else
{
// REMOVE this... or else it will print the world else somewhere
// i put this here to debug...
print "else<br/>";
?>
formatting your code helps a lot
EDIT: looking over the code, there's a lot of small issues everywhere. I'm not trying to be mean. I'm just saying... why don't you try to break the code up into smaller pieces and make sure all the parts will compile and work properly on their own before putting them all together? This is a lot to tackle all at once. Just try to dump your variables (arrays in particular) when you need to and each time you write a new chunk, make sure it works correctly and make sure everything else still works correctly. Then, move forward... it's easier to isolate problems that way.
this works for me. it uses pdo. oh, and now you don't need to worry about sql injection as much. this pretty much takes care of it completely. like everything, there's always ways around things but you do not need to check for magic quotes, you do not need to escape anything. doing the parameterization handles all that for you.
edit: so... when you write code... don't write a whole bunch of stuff and then see if it all works. write a few lines. test. write some more. test. make sure the new stuff works. make sure the old stuff still works. write a little more. i have absolutely no clue how you got that far with so many little issues. i'm not trying to be mean. write code in lil chunks, though. even logic. always test everything again, then move on.
and I left my debug statements in there... the print_r($array) and the var_dump(variable) so that you can see how that stuff is set up, where your values are coming from, what everything holds at whatever point, how to use them, where to put them. it will print weird things now. comment it out or remove them.
I understand there's a lot more tutorials for mysql_ functions but they are old and not safe at all. If you have issues using PDO, just come back to StackOverflow with your errors, issues and code and just write a disclaimer that "you know mysql_ functions are bad but the pdo is harder to learn" and people will be happy to help because it is that much better.
these are important PDO pages:
$stmt->bindParam()
$stmt->execute()
$stmt->rowCount() (I didn't use this but you might want it later)
$stmt->fetchAll() - for your select statements. this returns all the data in a huge array
how to prepare statements
and the code...
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// include('inc_header.php');
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function isValidEmail($Email) {
return filter_var($Email, FILTER_VALIDATE_EMAIL);
}
// ====================================================================================
// ====================================================================================
if (!empty($_POST)) {
print "<pre>This is your \$_POST array \n\n".print_r($_POST,true)."</pre>";
}
$error = '';
if (isset($_POST['add']))
{
// require('dbcon.php');
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');
// what if the array index ['whatever'] doesn't exist? errors.
// so we need to check and make sure it is set... then assign.
// this also gives us a blank default value, which is nice....
$id = isset($_POST['Id']) ? $_POST['Id'] : 'NULL';
$date = isset($_POST['Date']) ? $_POST['Date'] : '';
$list = isset($_POST['List']) ? $_POST['List'] : '';
$firstname = isset($_POST['Firstname']) ? $_POST['Firstname'] : '';
$lastname = isset($_POST['Lastname']) ? $_POST['Lastname'] : '';
$phone = isset($_POST['Phone']) ? $_POST['Phone'] : '';
$email = isset($_POST['Email']) ? $_POST['Email'] : '';
$calltime = isset($_POST['Calltime']) ? $_POST['Calltime'] : '';
$comment = isset($_POST['Comment']) ? $_POST['Comment'] : '';
if (!$list) {
$error .= "Please choose one<br />";
}
if (!$firstname) {
$error .= "First name is required<br />";
}
if (!$lastname) {
$error .= "Last name is required<br />";
}
if (!isValidEmail($email)) {
$error .= "The email entered is invalid<br />";
}
var_dump($error);
if (!$error)
{
$stmt = $conn->prepare("INSERT INTO contacts (id, date, list, firstname, lastname, phone, email, calltime, comment) \n".
" VALUES (:id, :date, :list, :firstname, :lastname, :phone, :email, :calltime, :comment) ");
$success = $stmt->execute(array(':id'=>$id, ':date'=>$date, ':list'=>$list, ':firstname'=>$firstname, 'lastname'=>$lastname,
':phone'=>$phone, ':email'=>$email, ':calltime'=>$calltime, ':comment'=>$comment));
if (!$success)
{
echo "\nPDO::errorInfo():\n";
print "<pre>".print_r($dbh->errorInfo(),true)."/<pre>";
}
else
{
print "it worked! the new row's ID is ".$conn->lastInsertId()."...!!!<br/>";
}
echo "Entered data successfully<br/><br/>";
} // end of if (!$error) { ... }
else
{
print "$error<br/>";
}
echo "<a href='contactsadd.php' style='font-color=#000000'>Back</a>\n";
} // end of if(isset($_POST['add'])) { ... }
else
{
// ====================================================================================
// ====================================================================================
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<?php print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><?phpprint(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>

Categories