Inputs array from while loop, passing $_POST for each input - php

<form role="form" autocomplete="off" action="includes/functions/fisa-init.php" method="POST">
<?php
connectDB();
$query = mysqli_query($mysqli, "SELECT * FROM `optionale`") or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($query))
{
?>
<span><?php echo $row['denumire']; ?></span>
<input type="text" name="nrBucati[]">
<input type="hidden" value="<?php echo $row['cod']; ?>" name="codProdus[]">
<?php } ?>
</form>
In the while loop I get an array for input name="nrBucati[]" and input name="codProdus[]".
I have the query:
$stmt3 = $mysqli->prepare("
UPDATE
`stocuri`
SET
`cantitate` = `cantitate` - ?
WHERE `cod` = ?
");
$stmt3->bind_param("is", $bucata, $cod);
// set parameters and execute
foreach( $_POST['nrBucati'] as $bucata ) {
return $bucata;
}
foreach( $_POST['codProdus'] as $cod ) {
return $cod;
}
if (!$stmt3->execute())
{
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
$stmt3->close();
I cannot manage to take all the input array values through $_POST. Detailed in:
While loop - Only one input from many others is sending a value through POST
How to get each input value from the arrays nrBucati[] and codProdus[] from HTML, through POST?

Something like this to properly assign/pair up your two params and then execute your query call from within the loop.
foreach( $_POST['nrBucati'] as $id => $bucata ) {
$cod = $_POST['codProdus'][$id];
if (!$stmt3->execute())
{
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
}

Run a foreach and prepare your data inside foreach loop:
// Get posted data and execute
foreach( $_POST['nrBucati'] as $key=>$bucata ) {
$cod = $_POST['codProdus'][$key]; // For object change this to $_POST['codProdus']->$key;
$stmt3= $mysqli->prepare("UPDATE `stocuri` SET `cantitate` = `cantitate` - ?
WHERE `cod` = ? ");
$stmt3->bind_param("is", $bucata, $cod);
if (!$stmt3->execute()){
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
$stmt3->close();
}

Related

My php variable reverts back to original value after resetting its value in a foreach loop

I have a php page that interacts with a database. I am trying to display data from the database as options for a user to select. I am trying to record which option a user selects but the variable I use ($a_game_id) to record which button is clicked gets reverted back to its original value after submitting another form. I have tried declaring the variable as global within the loop and using session variables.
$a_game_id = 9;//starting value - it changes from 9 as desired, but reverts back when another form is submitted
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
global $a_game_id;
// output data of each row
$results = $conn->query($sql);
$resultset = array();
while($a_row = $results->fetch_assoc()){
$resultset[] = $a_row;
}
foreach ($resultset as $row){
echo "<form action='display_lines.php' method='POST'>
<br>" . $row["away"] . " " . $row['away_spread'] . "---TOTAL AVAILABLE: " . $away_sum_array[$row['game_id']].
" <input type='submit' value='Bet " . $row['away'] ."' name='" . $row['game_id']."A' />
at " . $row["home"] . " " . $row['home_spread'] . "---TOTAL AVAILABLE: " .$home_sum_array[$row['game_id']]. "
<input type='submit' value= 'Bet " . $row['home'] ."' name='" . $row['game_id']."H' /> " . $row['date'] . "
</form>
<br>";
///HERE $a_game_id has gets the desired value
if(isset($_POST[$row['game_id'].'H'])){
$a_game_id = intval($row['game_id']);
}else if(isset($_POST[$row['game_id'].'A'])){
$a_game_id = intval($row['game_id']);
}
}
} else {
echo "<br> 0 results";
}
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
if(isset($_POST[strval($row['game_id']).'H'])){
echo '<h3>'.$row['game_id'].'<br>';
echo $row['home'].' '.$row['home_spread'].'<br>';
$team = $row['home'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
else if(isset($_POST[strval($row['game_id']).'A'])){
echo '<h3>' .$row['game_id'].'<br>';
echo $row['away'].' '.$row['away_spread'].'<br>';
$team = $row['away'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
}
if(isset($_POST['new_bet_submit'])){
//HERE $a_game_id reverts back to its original value which is undesirable
$sql3 = "INSERT INTO placed_bets (user_id, game_id, bet_amount, game_date) VALUES ('".$_SESSION['id']."', '".$a_game_id."', '".$_POST['new_bet_amount']."', '".$date."')";
echo $a_game_id.'<br>';
if ($conn->query($sql3) === TRUE) {
echo "<br><h3>BET PLACED SUCCESSFULLY</h3><br>";
} else {
echo '<h3>Error placing bet<br>';
echo $conn->error;
echo '</h3>';
}
}
Thank you for taking a look
Do you mean "when I make another request all my global variables get reset?" If so, yes, that's how they work. Each request is completely independent of others. They do not share variables or other data. All you get is what's in $_SESSION, $_GET, $_POST and $_COOKIE.
If you need to persist between requests you must put that in the session, the database, or something persistent.
If you're used to code where the process persists and the variables stick, like in client-side situations, that's a mode of thinking you need to completely abandon.

PHP deleting variable after new form

In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.
You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here
It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">

for each array combine for 3 or more arrays

Hello i am trying to submit an array of 3 textfileds from my form and then send to my database, table
my form
<input type="hidden" name="itemqt[]" value="<?php echo $item["quantity"]; ?>">
<input type="hidden" name="itemname[]" id="text-basic" value="<?php echo $item["name"]; ?>">
<input type="hidden" name="itemprice[]" id="text-basic" value="<?php echo $item["price"]; ?>">
basically when i attempt to combine two arrays it works
foreach (array_combine($_POST['id'], $_POST['itemprice'] ) as $name => $email)
{
echo "";
//$name . " - " . $email .
$ocode = $_POST['ocode'];
$sql = "INSERT INTO `orders` (pid, price,status,method,ocode, quantity) VALUES ('$name','$email','paid','Card','$ocode','$_POST[itemqt]')";
if (mysqli_query($con, $sql)) {
echo "";
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
}
}
but when i try to attempt to combine a 3 array, with another field like dis, it fails. i get a syntax error
foreach (array_combine($_POST['id'], $_POST['itemprice'], $_POST['itemqt'] ) as $name => $email, $qt)
{
echo "";
//$name . " - " . $email .
$ocode = $_POST['ocode'];
$sql = "INSERT INTO `orders` (pid, price,status,method,ocode, quantity) VALUES ('$name','$email','paid','Card','$ocode','$_POST[itemqt]')";
if (mysqli_query($con, $sql)) {
echo "";
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
}
}
please any idea, has someone successfully combined 3 arrays
array_combine makes result array from 2 arrays - one for keys and another for values. What do you expect by adding third array? It would be added to keys, to values? Where?
What you really need is just a foreach loop on some base variable, presumably $_POST['id']:
$i = 0;
foreach ($_POST['id'] as $id) {
// get values from other $_POST variables with the same key as $i
echo $id, ': ', $_POST['itemprice'][$i], ' => ', $_POST['itemqt'][$i];
$i++;
}
Or even simpler:
foreach ($_POST['id'] as $key => $id) {
// get values from other $_POST variables with the same key as $key
echo $id, ': ', $_POST['itemprice'][$key], ' => ', $_POST['itemqt'][$key];
}
And sure, you can check if $_POST['itemprice'][$key] or $_POST['itemqt'][$key] exist for a certain $key

PHP Multiple input search

I'm currently working on a bit of PHP and I've 3 text inputs. The values are searched in the MySQL database and should return whatever amount of results correspond with the entered criteria.
here is the search form:
<form id='SearchPersonal' method='post' action='businessUsersSearch.php' accept-charset='UTF-8'>
<fieldset >
<legend>Search</legend>
<div class='container'>
<label for='C_Name' >Business Name: </label><br/>
<input type='text' name='C_Name' id='C_Name' maxlength="50" /><br/>
<label for='C_County' >City: </label><br/>
<input type='text' name='C_County' id='C_County' maxlength="50" /><br/>
<label for='Job_Type' >Job Type: </label><br/>
<input type='text' name='Job_Type' id='Job_Type' maxlength="50" /><br/>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Search' />
</div>
</fieldset>
</form>
Here is the PHP script it links too in the action:
<?php
$mysqli_link = mysqli_connect("server", "database", "pass", "user");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_County', 'Job_Type');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "'$field' LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// builds the query
$query = "SELECT C_Name, C_StreetNumber, C_StreetName, C_Postcode, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Jobs.Job_Type, Jobs.Job_Price FROM Company INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$result = mysqli_query($mysqli_link, $query) or die(mysql_error());
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_assoc($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<hr><br>";
}
}
}
?>
For some reason it is returning that there is "
unexpected end of file
" however I've checked the code and all the codes is closed off correctly (from what I can see) when I add another '}' in at the end the script doesn't return anything at all. Anyone know why this would be happening?
Source:
Search MySQL Database with Multiple Fields in a Form
Because you forget to close
if(isset($_POST['submit'])) {// you not close the condition
At the end of your file
Just add } at end of your file
Fixed:
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_City', 'Job_Type', 'Review_Rate');
$conditions = array();
}
// builds the query
$query = "SELECT Company.C_Name, Company.C_StreetNumber, C_StreetName, C_Postcode, C_City, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Job_Type, Job_Price, Review_Rate, Review_Comment
FROM Company
INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID
INNER JOIN Review ON Jobs.Job_ID = Review.Job_ID";
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && !empty($_POST[$field])) {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "$field LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
echo "$query";
$result = mysqli_query($mysqli_link, $query);
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_array($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_City = $row['C_City'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
$Rating = $row['Review_Rate'];
$Comment = $row['Review_Comment'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>City: $C_City<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<br>Rating: $Rating<br>Comment: $Comment<hr><br>";
}
}
?>

Checking querystring values in PHP

http://localhost/?area=characters&name=Michal+Stroganof
$result = mysql_query("SELECT * from players WHERE name = '$_GET[name]'");
while ($row = mysql_fetch_assoc($result)) {
echo "Name: " .$row['name']. "<br>";
echo "Level: " .$row['level']. "<br>";
}
This is all code of my characters.php
If the get variable "name" is not included in the URL i want to show a search form that searches the table players. How would I do this?
Do you mean just to change your SQL string like so?
$sql = 'SELECT * from players';
if (isset($_GET['name'])) {
$safename = mysql_real_escape_string($_GET['name']);
$sql .= " WHERE name='$safename'";
}
$result = mysql_query($sql);
Be sure to sanitize your SQL!
Use isset():
if (isset($_GET['name'])) {
// your above code
} else {
// display form
}
Quick and dirty:
<?php
if (!isset($_GET['name']))
{
echo '<form action="'. $_SERVER['PHP_SELF'] .'" method="GET">'
.'<input type="text" name="name" />'
.'</form>';
}
else
{
// your current code that queries your database here
}
?>

Categories