Unknown column $cat_name in field list - php

I got the error: unknown column in field list, while I know for sure I haven't made any typos and the columns exist.
Anyone know what I'm overlooking?
<?php
//create_cat.php
include '../includes/connection.php';
$cat_name = mysql_real_escape_string($_POST['cat_name']);
$cat_description = mysql_real_escape_string($_POST['cat_description']);
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo "<form method='post' action=''>
Category name: <input type='text' name='cat_name' id='cat_name'/>
Category description: <textarea name='cat_description' id='cat_description' /></textarea>
<input type='submit' value='Add category' />
</form>";
}
else
{
//the form has been posted, so save it
$sql = 'INSERT INTO categories(cat_name, cat_description) VALUES ($cat_name, $cat_description)';
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
else
{
echo 'New category successfully added.';
}
}
?>

Try this:
$sql = "INSERT INTO categories(cat_name, cat_description) VALUES ('$cat_name', '$cat_description')";
Update:
You used ' to start a string. When doing this its not possible to use variables in the text, they will just be leaved as plain text. But when using " the variables will be evaluated.

The problem is your SQL query. You used single quotation marks, which is for a literal string. Your variables will not be parsed in. You need to use double quotation marks. Not only that, but for strings, you need to put single quotation marks around them when putting them into queries.
$sql = "INSERT INTO categories(cat_name, cat_description) VALUES ('$cat_name', '$cat_description')";
You should also try not to use mysql_* anymore. It's been depreciated (meaning it will be removed from PHP soon). Try looking at MySQLi (very similar to MySQL) or PDO instead.

Related

INSERT INTO statement won't insert a specific value correctly?

I am trying to use the INSERT INTO SQL statement in php. It will input everything correctly up until the last value ($bands_bio). Instead of putting in the correct information, it leaves the value blank. I have looked over everything and can't seem to find any sort of syntax errors.
$page_title = "Create a new band";
require ('includes/database.php');
require_once 'includes/bandsHeader.php';
$band_name = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_name', FILTER_SANITIZE_STRING)));
$band_photo = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_photo', FILTER_SANITIZE_STRING)));
$genre = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'genre', FILTER_SANITIZE_STRING)));
$band_bio = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_bio', FILTER_SANITIZE_STRING)));
echo $band_bio;
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = "")) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/searchFooter.php';
exit;
}
$albums = 0;
$sql = "INSERT INTO bands VALUES (NULL, '$band_name', '$genre', '$albums', '$band_bio')";
$query = #$conn->query($sql);
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/footer.php';
exit;
}
As you can see, I echoed out $band_bio in order to see if it was getting the right value from my form that uses the GET method, which it is so that's not the issue. It has no problem inserting everything correctly up until the last value, which is supposed to be the last column called band_bio in my bands table in my database. It will not output any errors or anything, either. It's almost as if it's taking the string data from the variable and removing all of the text before it inserts the information.
I have been working on this website for a few weeks now and have used the INSERT INTO statement the exact same way on other pages and it works just fine. This is the first thing that has really stumped me and I can't figure it out. Any help is appreciated.
When inserting, ensure that your pk (id) field is set to auto-increment.
This way, you can exert more control over your queries. You should be more successful with:
$sql = "INSERT INTO bands "
. "(`band_name`,`genre`,`numof_albums`,`band_bio`) "
. "VALUES ('$band_name', '$genre', '$albums', '$band_bio')";
By not specifying the pk field, INNODB will automatically increment and insert it for you.
The idea is that you want to specify which columns are being inserted into. Relying on column ordering by mysql is fine, but there may be something at play in your case.
There should be no reason why band_bio would be "left off". You would get a column-mismatch error.
Totally found the answer myself! It, in fact, was a syntax error.
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = ""))
The variable $band_bio was being assigned to a blank string in the if statement since I accidentally used an assignment operator rather than a comparison operator. So the correct code would need to be $band_bio === "" rather than $band_bio = "".
I swear, the problem is always something so much simpler than you think it's going to be.

mysql UPDATE query does not run

I want to update information. when I use the below in code is not working what is wrong in my code:
if(isset($_POST['submit'])){
$sql = "UPDATE `food`.`food_item`
SET `food_name` = '$_POST[food_name]',
`food_price` = '$_POST[food_price]',
`food_cat` = '$_POST[food_category]'
WHERE `food_item`.`id` ='$_POST[id]';";
$result = mysql_query($sql) or die("query not");
header("Location: product_info.php") ;
}
If you have a form input like,
<input type="text" name="product_name" />
You should get the value by,
$_POST['product_name'];
Is your form method is POST for GET?
If your method type is POST, you should get it like $_POST['input_name']
If your method type is GET, you should get it like $_GET['input_name']
Does all your input name you mentioned in html matches in php code?
Eg : If you have a form with input type,
<input type="text" name="product_name" />
Then, in php code, you should get it with what you entered in name attribute
$_POST['product_name'] OR $_GET['product_name']
Not something like,
$_POST['prod_name'] OR $_GET['prod_name']
Try this,
if(isset($_POST['submit'])
{
$food_name = $_POST['food_name'];
$food_price = $_POST['food_price'];
$food_cat = $_POST['food_category'];
$id = $_POST['id'];
// do not directly input the form data to sql, filter it by a special function mysqli_real_escape_string
// eg : $food_price = mysqli_real_escape_string($db, $_POST['food_price']);
// before executing the query, try to echo the each form input and sql query for clear picture.
$sql = "UPDATE `food`.`food_item` SET `food_name` = '$food_name',`food_price` = '$food_price',`food_cat` = '$food_cat' WHERE `food_item`.`id` ='$id'";
$result = mysqli_query($db, $sql);
if($result)
{
//header("Location: product_info.php") ;
echo "success";
}
else
{
echo "fail";
}
}
else
{
echo "form not submitted";
// use header to redirect to old page again
}
WARNING :
mysql is deprecated. Use mysqli or PDO.
Note :
$db is a database connection variable. You need to setup like
$db = mysqli_connect("localhost","username","password","database_name");
Look it's not mysql_connect, its mysqli_connect. Replace the db value according to your needs.
You can try following code to find the error.
echo mysql_error(); exit;
after following code.
$result = mysql_query($sql)
In order to access the array variables inside double quoted string, either do by enclosing them in curly brackets or put it outside the double quotes and append as a string. Here you try adding curly brackets like this:
if(isset($_POST['submit'])){
$sql = "UPDATE `food`.`food_item`
SET `food_name` = '{$_POST['food_name']}',
`food_price` = '{$_POST['food_price']}',
`food_cat` = '{$_POST['food_category']}'
WHERE `food_item`.`id` ='{$_POST['id']}';";
$result = mysql_query($sql) or die("query not");
header("Location: product_info.php") ;
}
Just echo $sql; Check what are the actual values in the query. Copy & run it in MYSQL query.
I think that you applied back ticks () on field names food_name . Remove back ticks & replace it with single quote ( ' )

Insert Into - php mysql

HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.

Allow user to submit comment based on (2) tables?

ERROR on this Php file:
<?php // Insert Comments into Database that user provides
//Get values of fields entered
$comment = $_POST['addComment'];
$pID4 = filter_var( $_POST['pID'], FILTER_SANITIZE_STRING );
$cID = $_POST['prefix'] . $_POST['code'];
require_once('inc/dbc1.php');
$pdo4 = new PDO('mysql:host=###;dbname=####', $username, $password);
$pdo4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
/* Error on this line --> */ $sth4 = $pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES('$comment',?,?);');
$sth4->execute(array($comment, $pID4, $cID));
?>
ERROR: syntax error, unexpected T_VARIABLE
From what I can see, the info field is required (i.e. cannot be null) but I can't see where you are setting the $info variable to pass into the prepared statement.
Try restarting mysql in debug mode, which should allow you to get the exact query being run - you can then see if it's a MySQL problem or a PHP problem.
You're not outputting your pID into your form, because of mal-formed string output:
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }
echo "</select>
<input type='text' id='addComment' name='addComment' tabindex='3' value='Enter comment' />
<input type='hidden' name='pID' value='<?php echo $pID4; ?>'>
^^^^^^^^^^^^^^^^^^^^^ here
</form>";
At the point I've indicated, you're still within the double-quoted string for the 'echo' command, so that PHP never gets executed, as it's within the string. What you'll end up with is an HTML tag that looks like
...<input type="hidden' name='pID' value='<?php echo 1234;?>'>...
in the browser, which is not what you want.
You really need to either "break out" of PHP mode, or use HEREDOCs. Either will let you output multi-line text chunks without having to jump through hoops with mixing quoting styles, and also let any decent syntax-highlighting editor catch errors such as this.
$pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES('.$comment.',?,?);');
that's wrong. use this:
$pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES(?,?,?);');

Update mysql table using POST

This is the query:
if (isset($_POST['editMessage'])) {
$result = mysql_query("UPDATE messages SET message = '".htmlspecialchars($editedmessage)."' WHERE id = '".$id."'");
if ($result) {
die("<strong>Message has been edited!</strong>");
} else {
die("<strong>Error ".mysql_error()."</strong>");
}
}
Using this form:
<form action="index.php" method="post">
<textarea name='editedmessage' rows='5' cols='70'><?php echo $_POST['editedmessage'];?></textarea>
<input type='submit' name='editMessage' value='Edit'>
It's not showing an error, it updates the table field, but doesn't enter the edited message into the field, so the field updates and shows no informtion at all.
Where am I going wrong?
htmlspecialchars($editedmessage)
You don't seem to be defining $editedmessage anywhere, did you mean $_POST['message1']
That should really be mysql_real_escape_string( htmlspecialchars( ... ) )
Try the other way when its correct you get an ressource back:
if(!$result) {
die('Died: ' . mysql_error());
} else {
echo "Edited:";
}
You're missing the line:
$editedmessage = $_POST['editMessage'];
You are wrong here
$result = mysql_query("UPDATE messages SET message = '".htmlspecialchars($_POST['editedmessage'])."' WHERE id = '".$id."'");
You use $editMessage in the query instead of _POST[editMessage] (unless you have register globals on, apparently you don't).
However, do NOT do this without running mysql_real_escape_string() on editMessage first, and DO NOT run htmlspecialchars() on it! Encoded data does not belong in the DB.
Either do $editMessage = $_POST['editMessage'];, or use _POST in the query directly, but wrap it in mysql_real_escape_string() for goodness sake!
However, you DO want to run htmlspecialchars(), htmlentities(), or at the very least string_tags() on $_POST['message1'] when you echo it out. This page is XSS (cross-site script) vulnerable.

Categories