I'm trying to write a php code to have a webpage insert information from a FORM into a DB.
I have managed to have the information from the form inserted correctly in the DB columns but when the user doesn't select ALL four items of the "checkbox" I get the following error message for every checkbox item not selected.
"Notice: Undefined index: ESPANOL in C:\xampp\htdocs\PHP\index1f.php on line 66"
I've been told the "isset" sentence could be the solution but I haven't been able to figure it out on my own.
HTML
<br>
Idiomas:<br>
ESPAÑOL:<INPUT type="checkbox" name="ESPANOL" value="s">
INGLES:<INPUT type="checkbox" name="INGLES" value="s"><br>
FRANCES:<INPUT type="checkbox" name="FRANCES" value="s">
PORTUGUES:<INPUT type="checkbox" name="PORTUGUES" value="s">
<br>
PHP
mysql_query("insert into alumnos2
(NOMBRE,APELLIDO,GENERO,ESTADO_CIVIL,ESTUDIOS,ESPANOL,INGLES,PORTUGUES,FRANCES,CLAVE)
values('$_REQUEST[NOMBRE]','$_REQUEST[APELLIDO]','$_REQUEST[GENERO]','$_REQUEST[ESTADO_CIVIL ]','$_REQUEST[ESTUDIOS]','$_REQUEST[ESPANOL]','$_REQUEST[INGLES]','$_REQUEST[PORTUGUES]','$_ REQUEST[FRANCES]','$_REQUEST[CLAVE]')",$x)
Note: the information is inserted in the database anyways.
Your query has a lot of columns that makes it hard to read. I would put the column names and values in an array and use that to construct the query. This approach also makes it easy to fill in only some values, and let the rest fall back on default values (such as NULL):
$values = array();
if (isset ($_REQUEST['ESPANOL'])) {
$values['ESPANOL'] = "''"; /* Indicating true */
}
if (isset ($_REQUEST['INGLES'])) {
$values['INGLES'] = "''";
}
/* ... */
$col_string = implode (',', array_keys ($values));
$val_string = implode (',', $values);
$query = "INSERT INTO alumnos2 ($col_string) VALUES ($val_string)";
Also:
You shouldn't use the deprecated mysql extention. Use PDO or mysqli instead.
Related
I have checkbox entries that I am appending to a list by their html name, like so:
Choose no more than three categories:<br>
<input id='category1' type="checkbox" name="boxsize[]"
onclick="CountChecks('listone',3,this)" value="asian">Asian
<input id='category2' type="checkbox" name="boxsize[]"
onclick="CountChecks('listone',3,this)" value="asianFusion">Asian Fusion
I have many other checkboxes as well. I then implode this list by doing:
$sanentry=implode(',',$_REQUEST["boxsize"]);
When I echo $sanentry I get a list of the selected values in the following format: asian, asian fusion. However when I try to send these values to my ethnicity table in mysql the ethnicity column is empty. Here is the post method and query I am using to send these values to my table.
$sanethnicity=mysqli_real_escape_string($con, $_POST['$sanentry']);
$sql3="INSERT INTO
ethnicity(restaurant_id,ethnicity)VALUES('$sanrestid','$sanethnicity')";
if ($con->query($sql3) === TRUE) {
echo "New record in ethnicity table created \n";
} else {
die("Error: " . $sql3 . "<br>" . $con->error);
}
mysqli_close($con);
?>
There is no problem with my restaurant_id column as that is being updated fine but for every new row inserted the ethnicity column always comes up blank. Does anyone know what I'm doing wrong?
enter image description here
Guessing the variable name is wrong. should be $sanethnicity you've got $ethnicitydb in your query.
$sql3="INSERT INTO ethnicity(restaurant_id,ethnicity) VALUES('$sanrestid','$sanethnicity')";
Also, is this the field that has raw ethicity array? $_POST['$sanentry'] or has that been imploded. You probably want this:
$sanethnicity=mysqli_real_escape_string($con, $sanethnicity);
Since the $sanethnicity was prior imploded from seomthing like:
$sanethnicity = implode(',',$_REQUEST["boxsize"]);
In this line your trying to use $sanentry as an entry in $_POST...
$sanethnicity=mysqli_real_escape_string($con, $_POST['$sanentry']);
Should be
$sanethnicity=mysqli_real_escape_string($con, $sanentry);
Although - you should be looking into using prepared statements and bind variables.
If you want to store it without losing the array structure then you should use serialize
I have a problem with default value for $_POST[];
So i have a html form with textboxes and the informations is sent to a php script. The php script has a sql query that is being sent to my database. But if my textbox in html form is empty the query doesnt have a value. So i want to set my post to a default value 0 so it returns a value atleast.
So here is an example of html form (This is not my actuall script. Just an example.
<form action="testscript.php" method="POST">
<input type="id" name="ID"/>
<input type="text" name="test"/>
<input type="submit" value="Send"/>
</form>
Ok so this script will send both id and test textboxes will always have a number value. And it sends the information to testscript.php
Here is testscript.php example
$conn = mysqli_connect('host', 'dbuser', 'dbpass', 'dbname');
$id = $_POST['id'];
$test = $_POST['test'];
$sql = "INSERT INTO test_table (id, test) VALUES ($id, $test)";
if (mysqli_query($conn, $query)) {
echo "Success";
} else {
echo "Failed" . mysqli_error($conn);
}
Alright so now if i submit my html form to php script without inserting any text to the textboxes the query will look like this
INSERT INTO test_table (id, test) VALUES ( , )
But the query should be like this
INSERT INTO test_table (id, test) VALUES (0, 0)
So. I know i can use value attribute in the html tag but then the value will be visible in the textbox and i dont want that.
And i know i can do an if statment to make a default value like this
if (isset($_POST['test'])) {
$test = $_POST['test'];
} else {
$test = 0;
}
But now the problem is that i would have to do that if statment for every textbox and my html form have more than 100 textboxes. So i dont want to make an if statment for every textbox because then my script will be way to big and it will take hours.
So is there any way to set a default value for all the textboxes without using if statment in php or value attribute in html form?
I know it seems like a pain but you MUST check that all inputs are valid. You can simplify the amount of code by using a ternary operator like this.
$id = isset($_POST['id']) ? $_POST['id'] : 0;
$test = isset($_POST['test']) ? $_POST['test'] : 0;
....
And no, it won't take hours even with hundreds of them.
To make this slightly less painful to code you can use the power of looping with PHP's variable variables
The most painful part will be creating an array with all your field names
$fields = array('id', 'test', 'extra', 'more', ..., 'one_hundred');
Then loop through that array creating variable names and at the same time escaping the strings - if they are there - otherwise set a value of 0 (zero). You might want/need to set this to "" (empty string)
foreach($fields as $field_name)
{
${$field_name} = isset($_POST[$field_name]) ? mysqli_real_escape_string($conn, $_POST[$field_name]) : 0;
}
You now have the variables $id, $test, $extra, $more, ...., $one_hundred available for your use.
If your checkboxes have unique names, then you'll need to check them on the server side to see if they actually have values in them one by one by using the ternary
isset($_POST["test"]) ? $_POST["test"] : 0
However, if your checkboxes are in array form:
<input type="checkbox" name="courses[]" value="1">
<input type="checkbox" name="courses[]" value="2 >
Then you could do the following:
foreach($_POST['courses'] as $course) {
echo $course; // etc etc etc
}
You can also set database defaults.
Another note, your code is prone to SQL injection. Although the question you have might simply be an example, you might just keep in mind there are better and safer ways of querying a database see PDO connections.
You can easily use null check and define your default value like this :
$name = $_POST['name'] ?? 'John';
in my case the default value is John if the name is not defined. It gives the same result like this :
$name = isset($_POST["name"]) ? $_POST["name"] : 'John';
I have a page where there are check boxes getting loaded dynamicaly so i dont know the number of check boxes (maximum of 50) and out of those check boxes users can select any number between 1 to 50 of checkboxes and can submit the form and on the action page i need get the values of all the checkboxes and insert them to database after checking for unoqueness like this
FIRST PAGE (FORM)
<?php while($the_DEATA_ARE_90=mysqli_fetch_array($getDOCS_30all)){ ?>
<div class="This_LISy_Lisy678" id="MAINDIV_DELEE<?=$the_DEATA_ARE_90['dcid']?>">
<div class="CHeck_IS_BOC">
<input type="checkbox" name="selecteddocx[]" value="<?=$the_DEATA_ARE_90['dcid']?>x<?=$the_DEATA_ARE_90['name']?>" id="check_docname<?=$the_DEATA_ARE_90['dcid']?>"/>
on the action page i am having this code
$selecteddocx = (isset($_POST['selecteddocx']) ? $_POST['selecteddocx'] : '');
$doocx = array();
$docxid = array();
foreach($_POST['selecteddocx'] as $value){
$str = explode("x",$value,2);
$doocx[] = $str[0];
$docxid[] = $str[1];
echo=implode(",", $doocx); // i need to print this for some reasons
echo implode(", ", $docxid); // i need to print this for some reasons
i am having this query to insert the coma sepertaed vales into database
i am converting the values of checkboxes into coma seperated values
$shaeredata=mysqli_query($conn,"insert into docs (dcid,pid) values ('$dcid','$pid')");
i i know i can insert the values into database in one shot like
$shaeredata=mysqli_query($conn,"insert into docs (dcid,pid) values ('$dcid','$pid'),('$dcid2','$pid'),('$dcid3','$pid'),('$dcid4','$pid')");
but i dont know how to do this as i am having the values in coma seperated (please note pid is same)
if checking of dcid can be done per pid then it will be great what i mean is thet insert only is dcid is not shared with pid (dcid already exists for that pid)
I'm trying to update a table of dishes with a new entry and cross reference it to an existing table of ingredients. For each dish added, the user is required to assign existing ingredients and the volume required on multiple lines. On submission, the Dish should be entered into the table 'Dishes' and the assigned ingredients should be entered into the 'DishIng' linked tabled.
My tables are set like this:
Table: "Dishes" Columns: DishID, DishName, Serves, etc...
Table: "DishIng" Columns: DishID, IngID, Volume
Table: "Ingredients" Columns: IngID, IngName, Packsize etc...
HTML:
DishID:
Name:
Catagory :
Serving:
SRP:
Method :
Source :
IngID:
Volume:
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
</ul>
<input type="submit">
</form>
Any suggestions for dymanically adding a row of ingredients in HTML would be very welcome.
PHP:
<?php
require_once('db_connect.php');
$DishID = mysqli_real_escape_string($con, $_POST['DishID']);
$DishName = mysqli_real_escape_string($con, $_POST['DishName']);
$DishCatID = mysqli_real_escape_string($con, $_POST['DishCatID']);
$Serving = mysqli_real_escape_string($con, $_POST['Serving']);
$SRP = mysqli_real_escape_string($con, $_POST['SRP']);
$Method = mysqli_real_escape_string($con, $_POST['Method']);
$SourceID = mysqli_real_escape_string($con, $_POST['SourceID']);
$IngID = mysqli_real_escape_string($con, $_POST['IngID']);
$Volume = mysqli_real_escape_string($con, $_POST['Volume']);
$array = array('$DishID', '$IngID', '$Volume');
$sql="INSERT INTO Dishes (DishID, DishName, DishCatID, Serving, SRP, Method, SourceID)
VALUES ('$DishID', '$DishName', '$DishCatID', '$Serving', '$SRP', '$Method', '$SourceID')";
$sql2 = "INSERT INTO DishIng (DishID, IngID, Volume) VALUES ('$DishID', '$IngID', '$Volume')";
$it = new ArrayIterator ( $array );
$cit = new CachingIterator ( $it );
foreach ($cit as $value)
{
$sql2 .= "('".$cit->key()."','" .$cit->current()."')";
if( $cit->hasNext() )
{
$sql2 .= ",";
}
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con));
}
echo "records added";
require_once('db_disconnect.php');
php?>
Currently on submit, it only updates the 'Dishes' table and gives me this message: '1 record addedError: 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 '('0','$DishID'),('1','$IngID'),('2','$Volume')' at line 1'
A high level of how you do this (although there are plenty of ways, this is just one with straight DB/PHP/HTML):
Your php will create a form to input the dish fields from the user.
Your php will then pull all of the ingredients from the ingredient table for that dish
Your php will iterate through the results returned from that query and for each result will:
Create a checkbox type input for the ingredient, and
Create a Text field type input for the ingredient and.
Create a Hidden field with the IngID
Once the user submits the form:
Your php will insert the to the dish table based on the dish fields on the form submitted.
Your php will iterate through the ingredients fields from the form submission and with each one will:
Determine if that ingredients checkbox is checked. If it is it will:
Insert into the DishIng table using the Hidden IngID field and the Volume field
Essentially, there is are two FOR loops. One to loop through the initial list of ingredients to make your form, and a second to loop through the form that is submitted. Each ingredient with a check mark will need it's own SQL INSERT statement to be added into the DishIng table.
How to iterate through SQL results in php: Iterate through Mysql Rows in PHP
How to iterate through Form fields in php: PHP loop through array of HTML textboxes
Because you are taking in user input and sticking it into a MySQL insert query, you'll also want to make sure you sanitize the inputs before submitting the query so you avoid some evil-doer from pulling some SQL injection and killing your DB.
Lastly: This is a pretty vague question so I anticipate it will be downvoted, and my response is also pretty vague. I only wrote it because it touches on an overall idea that is pretty common and is difficult to ask in a succinct way if you are just getting started with web development. You will probably get stuck quite a few times while writing this. Try narrowing down your problem to a single issue and take that issue/question to stackoverflow. You can also hit up Google, since everything you will need to do here has been written about on forums, blogs, wikis, and Q&A sites by a gajillion other folks.
I have a form that lists module id and also sub_module_id, for example
ADMIN === is parent module ID
users=== sub module id
here admin appears in the menu and users inside admin
now inside the form i have used checkbox like
[]Admin
[]Users
for parent module ID admin
<input id='module_permission[]' onclick=\"selectall()\" type='checkbox' value='".$key."' name='module_permission[]' $val_checked ><b>".$val."</b><br> ";
for sub modules
<input type='checkbox' id='sub_module_permission[$l][]' name='sub_module_permission[$l][]' value='".$key1 ."' onclick=\"selectParent($l);\" $val_checked>".$val1."<br> ";
when i click in check box its id get post and i need to insert to databse but i am unabale to insert the sub _module id in database
to post
$module_id=$_post[module_permission]
foreach($module_id as $key=>$value){
$sql2 = "INSERT INTO user_permissions(permission_id, employee_cd,module_id) values
(PERMISSION_ID_seq.nextval,'$employee_cd','$value')";
$this->db->db_query($sql2);
}
for sub _modules
$sub_module_id =$_POST['sub_module_permission'];
print_r($sub_module_id);
foreach($sub_module_id as $sub_key=>$sub_value)
{
echo $sub_value[1];
$sql4 = "INSERT INTO user_permissions(permission_id, employee_cd,module_id) values
(PERMISSION_ID_seq.nextval,'$employee_cd','$sub_value')";
HERE parent module id value get inserted in database but not the sub_module
please help
so what prints out when you print_r($sub_module_id); and echo $sub_value[1];?
And what does your query string look like after the vars are subbed in? echo $sql4;
Try running the the query string directly in SQL rather than through PHP. This will let you know if you have a SQL error or a PHP error. If the SQL is fine, add some error checking to your PHP so you can see where it fails. Usually I wrap all queries in something like:
if(!$result=$mysqli->query($query))
throw new Exception($query. " " .$mysqli->error);
From your comments and the now properly formatted code, it's possible to see that you are not referring to the 2nd dimension of your submoduleid. In otherwords you are trying to sub an array into your SQL statement.
This is what you have:
$sub_module_id =$_POST['sub_module_permission']; //a 2d array
print_r($sub_module_id);
foreach($sub_module_id as $sub_key=>$sub_value){
echo $sub_value[1];
$sql4 = "INSERT INTO user_permissions(permission_id, employee_cd,module_id)
values(PERMISSION_ID_seq.nextval,'$employee_cd','$sub_value')";
}
And this is what you need:
$sub_module_id =$_POST['sub_module_permission']; //a 2d array
print_r($sub_module_id);
foreach($sub_module_id as $sub_key=>$sub_value_arr){ //values are an array not a scalar
echo $sub_value_arr[1];
$sub_value= $sub_value_arr[1]; //get scalar for SQL
$sql4 = "INSERT INTO user_permissions(permission_id, employee_cd,module_id)
values(PERMISSION_ID_seq.nextval,'$employee_cd','$sub_value')";
}
Unrelated, but if you're getting that input from a form (and really, even if you're not), it's always a good idea to sanitize your SQL.