Error adding info to database via php [duplicate] - php

This question already has answers here:
PHP not posting information from database
(2 answers)
Closed 8 years ago.
I'm trying to add information to a database via PHP. However, when you submit the form it says "Error adding program." I've looked at the code and can't seem to find what's causing the error. Any advice?
Here's the form code:
<form name="Add" id="Add" method="post" action="programadd.php">
<p>Program Name:
<input name="program" type="text" id="program" />
</p>
<p>Air Date
<input name="air date" type="text" id="airdate" />
</p>
<p>Description
<input name="description" type="text" id="description" />
</p>
<p>Production
<input name="production" type="text" id="production" />
</p>
<p>Promotions
<input name="promotion" type="text" id="promotion" />
</p>
<p>Community
<input name="community" type="text" id="community" />
</p>
<p>Web
<input name="web" type="text" id="web" />
</p>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
And here's the code that adds the info into the db.
<?php require_once("db_connx.php");
$program = $_POST['Program'];
$airdate = $_POST['Air Date'];
$description = $_POST['Description'];
$production = $_POST['Production'];
$promotion = $_POST['Promotions'];
$community = $_POST['Community'];
$web = $_POST['Web'];
if (mysql_query ("INSERT INTO 'Content Calendar' (Program, 'Air Date', Description, Production, Promotions, Community, 'Web') VALUES ('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')"))
{ echo "Program successfully added to the database <br />";
}
else
{ echo "Error adding program"; }
require_once("db_connx_close.php");
?>

Do not use single quotes on column names , use backticks instead or let them be as it is.
The right way...
mysql_query ("INSERT INTO `Content Calendar` (`Program`, `Air Date`, `Description`, `Production`, `Promotions`, `Community`, `Web`) VALUES ('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')")
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !

Here is the issues
INSERT INTO
'Content Calendar' <--
(
Program,
'Air Date', <--
Description,
Production,
Promotions,
Community,
'Web' <--
They should all be enclosed with `` as
INSERT INTO
`Content Calendar`
(
Program,
`Air Date`,
Description,
Production,
Promotions,
Community,
Web
Thumb rules :
if you have a table name or colum name as "Some Name" meaning a space
in between then you must enclose them with back ticks ``
If you are using any reserved keywords they also must be enclosed
within backticks
http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html

Change these lines
if (mysql_query ("INSERT INTO 'Content Calendar' (Program, 'Air Date', Description, Production, Promotions, Community, 'Web') VALUES ('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')"))
{ echo "Program successfully added to the database <br />";
}
else
{ echo "Error adding program"; }
To
if (mysql_query ("INSERT INTO `Content Calendar` (`Program`, `Air Date`, `Description`, `Production`, `Promotions`, `Community`, `Web`) VALUES ('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')"))
{ echo "Program successfully added to the database <br />";
}
else
{ echo "Error adding program"; }

Related

what is failing in my insert query?

I have a form to submit with post, to my table in my database. However whenever I hit submit is says failure. I had several validation scripts that I removed to try and figure out why the form was not submitting.
I checked many of the answered questions regarding INSERT using mysqli_query, but none seemed to answer my question. I am aware the HTML structure is probably poor, this is just to get the script working correctly first. its really not complicated, I don't understand whats wrong here.
I have a registration form, and my other forms on the site I'm working on all work fine, update date their tables correctly. Don't know what I'm missing here.
<?php
include('db.php');
$event_name='';
$place='';
$time='';
$date='';
$description='';
$event_name=strip_tags($_POST['event_name']);
$place=strip_tags($_POST['place']);
$time=strip_tags($_POST['time']);
$date=strip_tags($_POST['date']);
$description=strip_tags($_POST['event_description']);
if(isset($_POST['submit'])) {
$query = "INSERT INTO user_posts (title, location, time, date, description)";
$query .= "VALUES ($event_name','$place','$time','$date','$description')";
if (mysqli_query($connection, $query)) {
echo "<h2> your post has been submitted </h2>";
}
else {
die('failure');
}
}
and the html form
<body>
<div class="box-1">
<form action="create_post_script.php" method="post" id="event_form">
<div class="box-2">
<input type="text" name="event_name" placeholder="event title" />
</div>
<div class="box-3">
<input type="text" name="place" placeholder="location" id="box-3" />
</div>
<div class="box-4">
<input type="time" name="time" id="box-4" />
</div>
<div class="box-4">
<input type="date" name="date" id="box-4" />
</div>
<div class="box-5">
<h4> <center> ... </center> </h4>
<textarea class="text-area" name="event_description" id="event_form" >
</textarea>
<input type="submit" value="submit" name="submit" placeholder="submit"/>
</div>
<div class="box-6">
<div class="box-7">
<h4> </h4>
</div>
</div>
</form>
</div>
When I hit submit, the resulting page confirms my connection and says 'failure', is this because of the way that I have the submit input field for the <text-area>?
try this
$query = "INSERT INTO user_posts (title, location, time, date, description) ";
$query .= "VALUES ('$event_name','$place','$time','$date','$description')";
you missing single quotes
<?php
$query = "INSERT INTO user_posts (title, location, time, date, description)";
$query .= "VALUES ('$event_name','$place','$time','$date','$description')";
// ^^^
// here missing single quotes
echo $query;
?>
Code look's fine, but only one thing you're missing a single quote ' in inserting values.
$query .= "VALUES ($event_name','$place','$time','$date','$description')";
Change To
$query .= "VALUES ('$event_name','$place','$time','$date','$description')";

error when try to insert data into database

HTML code
<form id="form1" name="addAnnouncement" method="post" action="ownerAddAnnouncement_exec.php" onsubmit="return validateForm()">
<label style="font-size:18px">Title:
<input type="text" name="title" />
</label>
<p>
<label style="margin-left: -36px; font-size:18px;">Description:
<textarea name="description" rows="6" cols="60"></textarea>
</label>
</p>
<label style="font-size:18px">Date & Time: <br>
From
<input type="text" name="from" /> <br>
To <input type="text" name="to" />
</label> <br>
<label style="font-size:18px">Venue
<input type="text" name="venue" />
</label>
<p>
<label>
<input type="submit" name="Submit" value="Submit" />
</label>
</p>
</fieldset>
</form>
PHP code
<?php
$title = $_POST['title'];
$description = $_POST['description'];
$from = $_POST['from'];
$to = $_POST['to'];
$venue = $_POST['venue'];
$link = mysql_connect("localhost","root","") or die();
$db = mysql_select_db("condo") or die("no database found");
$insert_sql="INSERT INTO announcement (title, description, from, to,venue, status)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
$sql_result=mysql_query($insert_sql) or die("Error in inserting data due to ".mysql_error());
if($sql_result)
echo "Succesfully insert new data. Please log in back";
else
echo "Error in inserting new data";
?>
an error like this ("Error in inserting data due to 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 'from, to, status) VALUES('melvin', 'sdsaadsd', 'wew', 'ewrerw', 'we3', 'Pendi' at line 1" )
is show out when try to insert a data into database.
Anyone please help me fix the code.i have been stuck at here for 1 hour.
Display the field names with in ``.
Convert the insert statement to
$insert_sql="INSERT INTO announcement (`title`, `description`, `from`, `to`,`venue`, `status`)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
You should escape reserved keywords using backticks. Currently, you are using the following reserved keywords - From and To Try this :-
$insert_sql="INSERT INTO `announcement` (`title`, `description`, `from`, `to`,`venue`, `status`)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
From is a keyword. And also To. It is not recommended to use them. But if you can't avoid it and still want to use them, add backquote ` like below in your insert query :
INSERT INTO announcement (`title`, `description`, `from`, `to`, `status`)
VALUES('$title', '$description', '$from', '$to', 'Pending')
Hope this helped.
Regarding current error it is about reserved keywords like from as field name, so to avoid it either rename your db column or enclose it in back-quotes like `from`
further you may face other errors as you are ignoring many good practices in your code, for example
Validate user input before inserting into db
remember to escape user input (sql injection)
enclose field names in back-quotes
and many others see http://code.tutsplus.com/tutorials/30-php-best-practices-for-beginners--net-6194

option from with php/mysql

I'm stuck on a posting script, I want information from mysql table 'category' from name to put that in mysql table 'post' to cat.
I cant get the data from category table in my html form "$row['name']
So when I click on sumbit the name from table 'category' example category called by 'name' test will be inserted into $cat
<html>
<body>
<title>ADD NEW POST</title>
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_post['cat'];
// insert data to mysql
$sql="INSERT INTO post(id, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if($result){
echo "Added a new post";
}
else {
echo "SOMETHING WENT WRONG!";
}
// end of post script ^^
?>
<?php
$query2 = mysql_query("SELECT * FROM `category` ");
while($row=mysql_fetch_array($query2)){
}
// html form start ?>
<form action="<?php $_PHP_SELF ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Picture link: <input name="pic" type="text" SIZE="80" id="pic"><br />
Youtube link: <input name="youtube" type="text" SIZE="80" id="youtube"><br />
Category game: <select name="name">
<option VALUE="<?php echo ''.$row['name'].''; ?>"><?php echo ''.$row['name'].''; ?></option>
<br /><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
You are vulnerable to SQL injection attacks. And if you have even bare bones minimal error handling in your code, you'd have been told WHERE the error is:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^^-- you **NEED** this
As for the actual problem:
$sql="
INSERT INTO post(id, pic, youtube, cat)
^^^^^^^^^^^^^^^^^^^^^--- FOUR fields
VALUES
('$id', '$title', '$pic', '$youtube', '$cat')";
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- FIVE values
You're missing title in the field list.
Never EVER assume success. Assume everything will fail, code accordingly, and treat success as a pleasant surprise.

Php mysql html form submission error

I'm working on a cms for my site and this form is not submitting. I know its a query problem, but I can't figure out whats wrong. Any help? Also, the $db is in my config and I do include it at the top of the page. The problem is its not submitting and all it does it refresh, nothing else. I also want to display there form submissions in a table later, but I don't know how to do that, if anyone can help me with that part that would be great as well.
php:
<?php
if(isset($_POST['submit']))
{
$c_name = $_POST['channel_username'];
$v_link = $_POST['video_link'];
$v_title = $_POST['video_title'];
$v_desc = $_POST['vido_description'];
$v_tags = $_POST['video_tags'];
$m_sources = $_POST['music_sources'];
$s_requests = $_POST['special_requests'];
if(empty($c_name) or empty($v_link) or empty($v_title) or empty($v_title) or empty($v_desc) or empty($v_tags))
{
echo 'You must fill in the first 5 fields.';
}
else
{
$getRank = $db->query("SELECT * FROM users WHERE username = '".$_SESSION['username']."'");
while ($row = $getRank->fetch_assoc())
{
$usename = $row['username'];
$rank = $row['rank'];
}
$db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES ('$username', '$rank', '$c_name', '$v_link', '$v_title', '$v_desc', '$v_tags', '$m_sources', '$s_requests')");
echo 'Form submitted successfully.';
}
}
?>
Html:
<form method="POST">
<p>Channel name <input type="text" name="channel_name" required>*</p>
<p>Video Link <input type="text" name="video_link" required>*</p>
<p>Video Title <input type="text" name="video_title" required>*</p>
<p>Video Description <input type="text" name="video_description" required>*</p>
<p>Video Tags <input type="text" name="video_tags" required>*</p>
<p>Music Sources <input type="text" name="music_sources"></p>
<p>Special Requests <input type="text" name="special_requests"></p>
<br></br>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
If the problem is indeed with the query, then it's probably this:
$db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES (''.$username.'', ''.$rank.'', ''.$c_name.'', ''.$v_link.'', ''.$v_title.'', ''.$v_desc.'', ''.$v_tags.'', ''.$m_sources.'', ''.$s_requests.'')");
I think instead, you want:
$db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES ('$username', '$rank', '$c_name', '$v_link', '$v_title', '$v_desc', '$v_tags', '$m_sources', '$s_requests')");
-- edit --
further to that, although it won't give you an error as-is, you really oughtn't insert fresh POST data in there. At the very least you probably want to use mysqli_real_escape_string on it.

PHP FORM INSERT INTO not inserting records

I'm working on a Uni assignment and am having trouble inserting records to MySQL database using a form. My set up is below.
I can view entries in the database with no problem. I'm new to this so sorry in advance :(
conninfo.php
<?php
$strServer="localhost";
$strDatabase="djdatabase"; // CHANGE TO YOUR DATABASE NAME HERE
$strUser="root";
$strPwd=""; // Leave blank for WAMPServer
$strDB=mysql_connect($strServer,$strUser,$strPwd)or die("Could not open database");
$database=mysql_select_db("$strDatabase",$strDB);
?>
addnewdata.php
<?php include "conninfo.php";
$newdj=$_POST["dj"]; //pick up from form
$newfn=$_POST["fn"];
$newem=$_POST["em"];
$newwe=$_POST["we"];
$newpi=$_POST["pi"];
$newev=$_POST["ev"];
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";
mysql_query($query);
header("location:showall.php");
?>
enternewdata.php
<?php include "conninfo.php";?>
<html>
<head>
</head>
<body>
<form action="addnewdata.php" method="post">
DJ Name:<input type="text" name="dj"><br>
FirstName: <input type="text" name="fn" /><br>
Email: <input type="text" name="em" /><br>
Website: <input type="text" name="we" /><br>
Picture: <input type="text" name="pi" /><br>
EventID: <input type="text" name="ev" /><br>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Many Thanks for your help :)
had better use SET command to insert data
$query = "INSERT INTO dj SET
DJName=".$newdj.",
FirstName=".$newfn.",
Email=".$newem.",
Website=".$newwe.",
Picture=".$newpi.",
EventNumber=".$newev."";
$save = mysql_query($query);
if($save){
header("location:showall.php");
}else{
die(mysql_error());
}
You are missing a quote ' wich is causing the error that you cannot see because you haven't done any debug. Anyway you should just change to this
'$newwe', '$newpi', '$newev')"; //a quote was missing after '$newv
I would suggest you to also debug query by adding or die('INVALID QUERY: ' . mysql_error());
so code would look like
mysql_query($query) or die('INVALID QUERY: ' . mysql_error());
Since you said this is an university test I don't know if you are supposed to use mysql_* function (wich are deprecated), but I would strongly reccommend to switch to mysqli or PDO if you can for security reason.
You missed ' on your query on $newev that gives you an error
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";

Categories