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
Related
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.
I am trying to make a program that asks for a user for their food allergies and what kind of category (Japanese, Chinese, etc) of food they want and then produce a list of restaurants that will accommodate them (displaying restaurant name). Users enter in their allergies by checkboxes they can select and select the category they want to eat by selecting a value in a dropdown. This is my code so far:
<?php
$con=mysqli_connect(root,user);
// Check connection
if (mysqli_connect_errno())
{
echo nl2br("Failed to connect to MySQL: " . mysqli_connect_error() . "\n");
} else {
echo nl2br("Established Database Connection \n");
}
//escape variables for allergen
$sanentry=implode(',',$_REQUEST["boxsize"]);
//escape variables for ethnicites
$category = mysqli_real_escape_string($con, $_POST['category']);
var_dump($category);
//sql select query
$sql="SELECT r.restaurant_name
FROM restaurant as r,
ethnicity as e,
allergen as a
WHERE e.restaurant_id=a.restaurant_id
AND e.restaurant_id=r.restaurant_id
AND a.restaurant_id=r.restaurant_id
AND a.allergen LIKE '%".$value."%'
AND e.ethnicity LIKE '%".$category."%'";
$split_allergy=explode(",", $sanentry);
// var_dump($split_allergy);
foreach ($split_allergy as $value){
echo $value;
$result=mysqli_query($con,$sql);
$resultCheck=mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row=mysqli_fetch_assoc($result)){
// echo $row['restaurant_name'] . "<br";
print_r($row);
}
}
}
mysqli_close($con);
$allergen=mysqli_real_escape_string($con, $sanentry);
?>
I put special characters because the allergens and categories were inserted with comma separated strings.The problem I am having is that the allergies are not being accounted for (when I select an allergy that is not associated with a restaurant that restaurant name is still being displayed). However when I change the $category value I get different results. My MYSQL query works when I run it in MYSQL, so it seems be a problem with the php. This leads me to believe something as wrong with my foreach loop (not properly inserting $value into the query when needed).
As a last note my echo $value is showing up correct (displays the correct allergens that were selected).
Does anyone see anything that I don't that could be causing this problem?
I'm trying to take an array and insert it into seperate rows in a MYSQL database.
Basically, there's an HTML form for a top 5 list that I want to input in one field, but with each value seperated by commas. So, for example (Artist 1, Artist 2, Artist 3, etc.)
These 5 values then have to be seperated into 5 values that are then inserted into 5 rows in a MYSQL database.
So the HTML form looks like this:
<tr>
<td>Loud Rock</td>
<td><label for="lr_topfive"><input type="text" placeholder="" name="lr_topfive" size="75"
maxlength="100" autofucus required /></label></td>
</tr>
and the form value is sent to another php file with this code in it:
$val = $_POST['lr_topfive'];
$data = str_getcsv($val);
??????
$lr_one = mysql_prep($_POST['lr_one']);
$lr_two = mysql_prep($_POST['lr_two']);
$lr_three = mysql_prep($_POST['lr_three']);
$lr_four = mysql_prep($_POST['lr_four']);
$lr_five = mysql_prep($_POST['lr_five']);
$query = "INSERT INTO xyz_wb (lr_one, lr_two, lr_three, lr_four, lr_five) VALUES ('{$lr_one}','{$lr_two}', '{$lr_three}', '{$lr_four}', '{$lr_five}')";
$result = mysql_query($query, $connection);
if ($result) {
redirect_to("email-ready.php");
} else {
//display error message
echo "<p>Yikes!</p>";
echo "<p>" . mysql_error() . "</p>";
}
I get that the 'lr_topfive' value is parsed and seperated into distinct values by the first two lines, but I dont know what to do before inserting these values into the MYSQL DB.
I think you are just looking for:
$top_five_array = explode(',', $_POST['lr_topfive']);
and then:
$lr_one = mysql_prep($top_five_array[0]);
$lr_two = mysql_prep($top_five_array[1]);
....
However, this will break if there are not exactly 4 comma's in your input field.
Apart from that you need to switch to prepared statements using PDO or mysqli, see the comments below your question.
I am trying to make a category and sub category option in which sub-category will be selected according to the category . I am using ajax for this . In the php script I am using file() to read the sub categories . Now although sub-categories are appearing in my site , its value is not inserted into the database . M confused . Here are the codes :
$arr = file(SUB_CAT_DIR.$val);
echo '<select name="ad_sub_category">';
foreach($arr as $line)
{
echo '<option value="'.$line.'">'.$line.'</option>';
}
echo "</select>";
And php script to insert into database :
$sql = "
INSERT INTO
tbl_classified
SET
classified_id = '$id',
classified_category = '$info[ad_category]',
classified_sub_category = '$info[ad_sub_category]'
Is this MySQL? You havent said..
Normally I'd have expected to see
Insert into mytable (field1,field2,field) values('$field1','$field2','$field3')
Have you tried getting the value of $sql as a string, echo it to screen, and then run it direct through the command line, to check errors? or to confirm your SQL statement is being formed? Have you run the mysql_error function in case its complaining its a dup or something (see http://us3.php.net/mysql_error)
Need a little help...
I have a basic html table with text field form in last column and a hidden field on each row of the web table. The data in this table is extracted out of a table in the database.
I want my users to be able to update one field in the database (a score) using this web form (page).
I have a hidden web form component on each row that contains the unique id of the record in the database for each row in the web page table.
I was attempting to create code that would update the entire list of entries on the web form, even if the user is not updating that particular field. (The values of the scores field are populated into the web form at the creation of the table. So if you did not update any scores, but hit the submit button, it would update the database table with the same values.)
Here’s my code: (abbreviated to save bytes…)
<?php
//Do all the database connection stuff up front
if (isset($_POST[‘score’]))
{
$student_id = $_POST[‘student_id’];
$score = $_POST['score'];
$n = count($score);
$i = 0;
echo "You have updated these student scores on this assignment. \r\n" .
"<ol>";
while ($i < $n)
{
echo "<hr><P>{$score[$i]} \r\n";
echo "<hr><P>{$student_id[$i]} \r\n";
$qry = "UPDATE assignments SET score = ".$score[$i]." WHERE student_id = " .$student_id[$i]. '"';
$result=#mysql_query($qry);
$i++;
}
}
if($result) {
header("location: member-index.php");
exit();
}else {
die("Query failed");
}
?>
Am I on the right track? Is there a better way to do what I’m attempting? All suggestions and ideas welcome!
Thank you in advance!
i'm guessing you are using
<input name="scores[]"/>
why not echo the unique id into the input name?
<input name="score[<?php echo $unique_id ?>]" />
this means in the loop, the $i would be the unique id (one less variable and less HTML).
and please use mysql_real_escape_string() when working with DB transactions. I know it's an example code but please don't forget that
Besides that, yes, you are on the right track