This question already has an answer here:
I am creating two level dropdown select box with PHP, MYSQL and JQuery. Everything seems fine but when my parent category doesn't have child or if I doesn't select child it is giving me error and I can't understand what this error means and how to resolve. I need you guyz help.
Error: Notice: Undefined index: f_child_cat in C:\xampp\htdocs\pathtofile\index.php on line 58 You selected 12 & 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 1
Here is my front end code
<?php if(isset($_POST['submit'])){
$drop = $_POST['first_child_cat'];
$f_child_cat = $_POST['f_child_cat'];
echo "You selected ";
echo $drop." & ".$f_child_cat;
$query = mysql_query("SELECT * FROM qa_categories WHERE parentid = $f_child_cat")
or die(mysql_error());
echo '<ul>';
while($cats = mysql_fetch_array( $query ))
echo '<li>',$cats['title'],'</li>';
echo '</ul>';
}
?>
</div>
It means that $_POST['f_child_cat']
is not defined (doesn't exist). You should be using binded parameters to prevent against SQL injection and use mysqli_
or PDO
functions.
Since this is part of your query, I would recommend that you wrap your query like so:
if( isset($_POST['f_child_cat']) && !empty($_POST['f_child_cat']) ) {
... call db
}
else {
echo "You didn't select this"
}
$_POST['f_child_cat']
is not defined check if the value is present first before using it.
$f_child_cat = isset($_POST['f_child_cat'])?$_POST['f_child_cat']:false;
if ($f_child_cat){
$f_child_cat = mysql_real_escape_string($f_child_cat); // always escape
/// your query.
}
Note: mysql_* functions are depricated, use mysqli or pdo as an alternative.