I have a script that allows for multiple rows to be created on the page and then I need to have the rows counted on the post and then each row inserted into the table.
I have the GUI working to where users can add or remove rows as needed yet when I submit no data is being written to the table. I have tried altering the script for the post to be straight '$variables' and it works to write but only writes the first row.
I have attached the action script that I am using from WebLesson that works great for one field but for more than one I am at a loss for what to try.
//includes
include '----';
include '---';
session_start();
$number = count($_POST['name']);
echo $_POST['name'] . "<br>";
echo $number . "<br>";
if($number >= 1)
{
echo $_POST['pasid'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id = $_POST['pasid'];
$name = $_POST['name'];
$dose = $_POST['dose'];
$dir = $_POST['directions'];
$time = $_POST['time'];
echo $i;
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO meds (id, name, dose, directions)
VALUES('".mysqli_real_escape_string($_POST["pasid"][$i])."',
'".mysqli_real_escape_string($_POST["name"][$i])."',
'".mysqli_real_escape_string($_POST["dose"][$i])."',
'".mysqli_real_escape_string($_POST["directions"][$i])."',
'".mysqli_real_escape_string($_POST["time"][$i])."') " ;
mysqli_query($conn, $sql);
}
}
echo "Data Inserted";
}
else
{
die("Connection failed: " . mysqli_connect_error());
}
I would like this to count how many rows were posted and then submit each row to the table.
Picture of the UI:
You can generate unique name attributes for each form element and then loop through them in PHP. The easiest way to do that would probably be increment a number at the end of the name attribute each time the user creates a new row. You will have to do that with Javascript.
var suffix = 0;
function addNewRow(){
...
<input type="text" name="pasid_${i}"/> //Add incriminating suffix
...
suffix++; //Increment suffix for next time
}
Then your PHP would look like
$suffix = 0;
while(isset($_POST['pasid' . $suffix])){ //Keep looping until no more POST value
//Process row $suffix, referencing all the data like $_POST['field_name'. $suffix]
$suffix++; //Increment suffix for the next field
}
Make sure the field you are checking for in the while loop is required or else the user might omit an input and the loop would terminate prematurely. You could also check multiple $_POST indexes in the while loop if non of the fields are required.
Related
I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)
I am trying to add data into tuples of the columns create in the tables of a database. The form is dynamic adding numerous input fields when required by the user.
The database is created from one input field.
The tables are created from other input fields
The columns are created from one input box and split to create the columns linking to the tables.
Now I am trying to add data into the columns created
$dbConnectionT = mysqli_connect($host, $user, $password, $dbName);
$counter = 0;
// create loop to assign input boxes together
foreach($combined as $message => $answer)
{
// replace the white space from input box to database data type and data length
$columns = "`".str_replace(" ", "` TEXT(60), `", $answer)."` TEXT(60)";
// create the tables and columns from the message text box
$sqlCreateTable = "CREATE TABLE " . $message . "( " . $columns . " )";
echo "</br>";
$counter ++;
// if the connection and sql query is true echo for debugging
if ($dbConnectionT->query($sqlCreateTable) == TRUE)
{
echo "{$message} = {$answer}";
echo "</br>";
echo "Message " . $counter . " is sent ";
echo "</br>";
}
}
So I am trying to add an input form in the php next to the columns of the tables, which is answer! So i can add data into them tuples.
Please note I understand this is bad database work, although this is not going live and just learning PHP.
Thanks in advance
This is the output I get
Database one was created
RFq = Id item price
Message 1 is sent
quote = qid item price
Message 2 is sent
And I would like a text box next to the "Id Item Price" to be able to insert into them columns of the database
I have a HTML form that retrieves a varying number product types that the user inputs stock figures. This data then needs to be INSERTED to a new table.
Here is the PHP query that populates the form.
require_once 'config.php';
$i = 1;
$sql = "SELECT * FROM dealer_product WHERE customer_code='$custcode' ORDER BY prod_code";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$prodcode = $row['prod_code'];
echo "<tr><td><input type='text' name='prod".($i++)."' value='" . $prodcode . "'/></td><td><input type='number' name='openstock".($i++)."'/></td><td><input type='number' name='sold".($i++)."'/></td></tr>";
}
mysql_close($con);
?>
I know how to INSERT a set number of multiple records, but how do I INSERT a varying number of records?
Thanks in advance. Sorry for my basic knowledge, I'm a network admin not PHP MYSQL.
Name your input fields as if they were arrays, e.g.:
<input name="prods[0]" />
You can then output a variable number of inputs in your HTML, even add more with JavaScript. PHP will convert the input to an array over which you can iterate:
<?php
foreach ($_POST['prods'] as $prod) {
/* Process $prod */
}
?>
I recommend that you go in the same way but using
while ($row = mysql_fetch_assoc($result))
And now you have not numbers as index that is more complicated way to see things, better see associative way that's the column name from your table in mysql.
And you're doing a lot of increments there doing $i++ a lot of times. I don't know if you're doing that intentionally but if not just increment $i once.
Also the number of row can be reached using this:
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
Look inside the manual
http://us1.php.net/mysql_fetch_assoc
I'm working on a little system for SecondLife which involves a bit of heavy use of databases & I've run into a problem I can't for the life of me solve.
I'm trying to run a query that selects an entire row based on two different column values. I'm using the $_GET[''] call to identify which details I need, and then I need to pull all the data from the entire row and echo it onto a blank page.
Now, I got it to work at first, but it was pulling ALL the rows created by a UUID and echoing them, when I only needed a specific. Then I tried to get it to work with a second identifier (which is a column called 'field' for the purpose of testing), and that's pretty much where I lost it.
I just need to select one row that has two exact values, and I need it to be draconian so it only selects a row that has both and not just one of the two.
Any ideas?
Script enclosed (don't mind the mess or the commented out code which I kept for reference; I am going to clean the script once I get it working!)
<?php
// Get key from the parameter.
$avatar_key = $_GET['key'];
// Quest params.
$questname = $_GET['questname'];
$questid = $_GET['id'];
// Connect to the database. $con holds connection info.
$con = mysql_connect("localhost","user","pass");
// Error checking.
if(!$con)
{
die('Could not connect: '.mysql_error());
}
// Select the DB we want.
mysql_select_db("yyyyy_slcom",$con);
// Build the query.
$query = "SELECT * FROM sldb_data WHERE sldb_data.uuid = '$avatar_key' AND sldb_data.field = '$questname'";
/*$query = "select * from (
select uuid, field, value, progress, ROW_NUMBER() OVER (PARTITION BY uuid ORDER BY progress DESC)
";*/
// Run the query, store the result in variable $result.
$result = mysql_query($query);
if(!result)
{
die('Error: ' . mysql_error());
}
// Check how many rows we got back with our query.
$rows_returned = mysql_num_rows($result);
echo $row['field'];
// If we get anything back,
if($rows_returned > 0)
{
//echo $row['field'] . ' was found.' . $questname;
/*if(!$row['field'])
{
echo 'You are not on this quest yet.';
}
elseif(($row['field']) && ($row['value'] == "notstarted"))
{
echo 'This quest hasn\'t started yet.';
}
elseif(($row['field']) && ($row['value'] == "started"))
{
echo 'You are on quest: "' .$row['field']. '"';
}*/
/* $fields = mysql_list_fields("tenaar_slcom","sldb_data");
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
if(in_array($quest, $field_array))
{
echo 'Your quest is ' . $row['field'];
}
elseif(!in_array($questname, $field_array))
{
echo 'You are not on this quest yet.';
}
elseif((in_array($questname, $field_array)) && ($row['value'] == "notstarted"))
{
echo 'You have not started quest "' .$row['field']. '" yet.';
} */
// cycle through and print what we got.
//while($row = mysql_fetch_array($result))
//{
//echo 'Quest name: ' . $row['field'] . ' | Progress: ' .$row['value'] . '<br />';
//}
}
/*else
{
echo 'You are not on this quest yet.';
}*/
// Close the connection.
mysql_close($con);
?>
You appear to be missing a step in-between the time you get the number of rows and when you print out the field. You need to actually store the results of the query in the $row array.
$rows_returned = mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo $row['field'];
I am creating a user registration form with simple requirements.and insert data with simple query
<?php
if (isset($_POST) && isset($_POST["form_register"]))
{
$insert_query = "INSERT INTO users SET
users.first_name='" . mysql_real_escape_string($_POST['fname']) . "',
users.last_name='" . mysql_real_escape_string($_POST['lname']) . "',
users.email='" . mysql_real_escape_string($_POST['email']) . "',
users.password='" . mysql_real_escape_string($_POST['password']) . "';";
if (mysql_query($insert_query))
{
$_SESSION['messageType'] = "success_msg";
}
else
{
$_SESSION['message'] = "-Registration not Successful.";
$_SESSION['messageType'] = "error_msg";
}
}
?>
but now I have 3 extra fields in this form. If I select a checkbox then the other 2 field data go in another table with having this data also. how can i do that?
It is my old code...now I add 3 new columns, 1 checkbox and 2 text boxes.
The query is, if checkbox is selected then other 2 colums values go in another table and if checkbox is not select then working 1 query.
If I understand right you want to insert data in another table IF user check the checkbox.
So you have to use another IF like this:
if (mysql_query($insert_query))
{
if (/* here your condition for checkbox*/)
{
/* here your query for the secund table and the new two values*/
}
$_SESSION['messageType'] = "success_msg";
}
Note that is extremely important you run the secund query after the success of the first, cause if the first fails for some reason, secund will not be executed.
We really need to see your form as what you're providing us is way too vague, also, check the ending syntax for your $insert_query.
If I comprehended the question right, the final code should look something like this.
Tell me if I'm wrong
<?php
if(isset($_POST) && isset ($_POST["form_register"])){
$insert_query1 = "INSERT INTO users SET
first_name='".mysql_real_escape_string($_POST['fname'])."',
last_name='".mysql_real_escape_string($_POST['lname'])."',
email='".mysql_real_escape_string($_POST['email'])."',
password='".mysql_real_escape_string($_POST['password'])."'";
if(mysql_query($insert_query)){
$_SESSION['messageType'] = "success_msg";
} else {
$_SESSION['message'] = "-Registration not Successful.";
$_SESSION['messageType'] = "error_msg";
}
if($_POST['checkbox']) {
$insert_query2 = ""; //Put your second MYSQL Query here
}
if(mysql_query($insert_query2)){
$_SESSION['messageType2'] = "success_msg";
} else {
$_SESSION['message2'] = "-Registration not Successful.";
$_SESSION['messageType2'] = "error_msg";
}
}
?>