Push items to PHP array using a form - php

I am trying to add items to an array each time I submit the form above it.
The first 2 items you see in the screenshots are hardcored for the example.
The third item which is a long code is the item I pull from my database and then push it into the array.
My problem is that every time I submit the form to add a new item into the array the new item simply overwrites the previous one as you can see in the screenshots below.
insertProduct.php
$inserted_product_code = $_POST["code"];
$sql = "SELECT products.code FROM products WHERE products.code = '$inserted_product_code'";
if($result = mysqli_query($link, $sql)){
while ($row = mysqli_fetch_assoc($result)){
array_push($inserted_products, $row['code']) ;
}
}
echo print_r($inserted_products);
createTable.php
$inserted_products = array("Entry 1","Entry 2");
<form method="POST" action="">
<input type="text" name="code" placeholder="Your Input" required />
<button type="submit" name="insertProduct"> Submit </button>
</form>
if (isset($_POST['insertProduct'])) {
include 'insertProduct.php';
}

I tried to implement the same using sessions, that works fine for me,
if (isset($_POST['insertProduct'])) {
$inserted_code = $_POST['code'];
$inserted_products = array("Entry 1", "Entry 2");
if (isset($_SESSION['myArray'])) {
$inserted_products = $_SESSION['myArray'];
array_push($inserted_products, "Entry $inserted_code");
$_SESSION['myArray'] = $inserted_products;
} else {
array_push($inserted_products, "Entry $inserted_code");
$_SESSION['myArray'] = $inserted_products;
}
}

Related

PHP code inserts into sql db with text box inputs but not with select options (dropdowns)

Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....

Select all data after selecting another option

I am trying to create a submission on a form where I can show all results from a table as well as show individual results. I can achieve the page load to show all until the form is submitted, however when I then try and select all again im struggling.
On page load im simply doing:
<?php
if (isset($_POST['submit'])) {
$teamData = $_POST['teamData'];
var_dump($teamData);
$sql = "SELECT * FROM team WHERE dashboardId = 1 AND id = $teamData";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$teamName = $row['name'];
}
}
} else {
$teamName = 'All';
echo 'no submission yet';
}
?>
Setting the variable to say 'all'
<p>Team: <?php echo $teamName; ?></p>
Once an option has been selected it check the database and uses the name of and sets it. However in the dropdown list if i want to show all results again i get an error of:
Undefined variable: teamName
which makes sense because of my form:
<form method="POST" action="">
<select name="teamData">
<option selected value="" disabled>Select your team</option>
<option value="allTeamData">All team data</option>
<?php teamMembers(); ?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
I am just struggling to understand the logic of how to select all again from the drop down.
$teamName = 'All'; // Initialise the variable at top
// Change the condition to this for better restriction
if ($_POST && isset($_POST['submit'])) {
$teamData = $_POST['teamData'];
var_dump($teamData);
$sql = "SELECT * FROM team WHERE dashboardId = 1 AND id = $teamData";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$teamName = $row['name'];
}
}
}

PDO Echoing Duplicate Results

I need to echo a download button if there are certain correct results, but when I echo the download button it decides to echo more than 1. How do I correct this?
heres my code:
<?php
$u = $_SESSION["username"];
$getscripts = $conn->prepare("SELECT * FROM project_sa");
$getscripts->execute();
while ($row = $getscripts->fetch(PDO::FETCH_BOTH)) {
$sec = $conn->query('SELECT * FROM us WHERE username="wafflezzz"');
$sec->execute();
while ($rowx = $sec->fetch(PDO::FETCH_BOTH)) {
$checker = $rowx[$row["script_title"]];
if ($checker == $row["script_title"]) {
$geturl = $conn->prepare("SELECT * FROM project_sa WHERE script_title='$checker'");
$geturl->execute();
while ($row = $geturl->fetch(PDO::FETCH_BOTH)) {
echo '
<form method="post" action="dl.php">
<input name="bname" value="<?php echo $branded_m_img_url; ?>" hidden></input>
<input type="submit" class="ui huge button" value="Download"></input>
</form>';
}
}
}
}
?>
It returns about 2 broken duplicate entries when there is only 1 entry in the database!
"You have nested while loops, that's why you get duplicate entries, you also overwrite $row in the inner while loop – Alon Eitan yesterday"
After I fixed that, it worked!

I can't get my update query to work (php / mysqli)

I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>

Using PHP to add numeric values to two MySQL database rows

I have a site in which logged in users can accumulate points which they can later buy with via a shopping cart. The page below is an admin php feature in which an Admin can give points to an individual user (one user at a time for now).
There are three tables involved with this script:
users: contains the users details
tally_point: stores all of the points transactions, both incoming and ordering
reward_points: stores the total amount of points that the user has
The script retrieves the users’ details via a drop down menu and adds the points to the tally point table ok but....
<?php # add-points-ind.php
// This is the main page for the site.
// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');
// Set the page title and include the HTML header.
$page_title = 'Add Points to User';
include ('includes/header_admin_user.html');
// If no dealer_code variable exists, redirect the user.
if (!isset($_SESSION['admin_int_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
?>
<h1>Add Points to User</h1>
<div id="maincontent_inner">
<div id="maincontent_inner2">
<?php //add-points-ind.php
// This page allows the admin to add points to an individual user
require_once ('mydatabase.php'); // Connect to the database.
if (isset($_POST['submitted'])) { // Check if the form has been submitted.
// Check if points were submitted through the form.
if (is_numeric($_POST['tally_points_in'])) {
$p = (float) $_POST['tally_points_in'];
} else {
$p = FALSE;
echo '<p><font color="red">Please enter the pointås!</font></p>';
}
// Validate the User has been selected
if ($_POST['selected_user'] == 'new') {
// If it's a new categories, add the categories to the database.
$query = 'INSERT INTO tally_points (users_id) VALUES (';
// Check for a last_name.
if (!empty($_POST['users_id'])) {
$query .= "'" . escape_data($_POST['users_id']) . "')";
$result = mysql_query ($query); // Run the query.
$a = mysql_insert_id(); // Get the categories ID.
} else { // No last name value.
$a = FALSE;
echo '<p><font color="red">Please enter the Dealers name!</font></p>';
}
} elseif ( ($_POST['selected_user'] == 'existing') && ($_POST['existing'] > 0))
{ // Existing categories.
$a = (int) $_POST['existing'];
} else { // No categories selected.
$a = FALSE;
echo '<p><font color="red">Please select a registered Dealer!</font></p>';
}
if ($p && $a) { // If everything's OK.
// Add the print to the database.
$query = "INSERT INTO tally_point (users_id, tally_points_in, order_id, total, tally_points_entry_date) VALUES ('$a', '$p', '0', '0', NOW())";
if ($result = mysql_query ($query))
{
// Worked.
echo '<p>The reward product has been added.</p><br />Go back<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
} else {
// If the query did not run OK.
echo '<p><font color="red">Your submission could not be
processed due to a system error.</font></p>';
}
} else { // Failed a test.
echo '<p><font color="red">Please click "back" and try again.</font></p>';
}
} else { // Display the form.
?>
<form enctype="multipart/form-data" action="add-points-ind.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
<fieldset>
<legend>Add Points Individually:</legend>
<p><b>Select User:</b></p>
<p>
<select name="existing"><option>Select One</option>
<?php // Retrieve all the users details and add to the pull-down menu.
$query = "SELECT users_id, users_sale_id, users_first_name, users_surname FROM users ORDER BY users_surname ASC";
$result = #mysql_query ($query);
while ($row = #mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo "<option value=\"{$row['users_id']}\">{$row['users_sale_id']}: {$row['users_first_name']} {$row['users_surname']} </option>\n";
}
#mysql_close($dbc); // Close the database connection.
?>
</select></p>
<span class="extras"><input type="radio" name="selected_user" value="existing" /> Please confirm this is the correct user</span>
<p><b>Points:</b> <br />
<input type="text" name="tally_points_in" size="10" maxlength="10" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden"name="submitted" value="TRUE" />
</form>
<?php
} // End of main conditional.
?>
<br class="clearboth" />
End text
</div>
<?php // Include the HTML footer file.
include ('includes/footer_admin_user.html');
?>
... Im having trouble with getting the new points added to the points total field (reward_user_points) in the reward_points table, I have some code below but Im not sure where I am supposed to put it, if anyone has any suggestions please let me know.
<?php
$query = "SELECT reward_user_points FROM reward_points WHERE users_id = $a";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$TotalPoints = $row['reward_user_points'];
if (#mysql_affected_rows($dbc) == 1) { // Whohoo!
$new_credit = $TotalPoints + $p;
$query = "UPDATE reward_points SET reward_user_points ='$new_credit' WHERE users_id = $a";
$result = #mysql_query($query);
}
?>
Ok, I have to say that I don't understand very well what your trouble is. You say you're having trouble with getting the new points added to the points total field, but could you be a little more specific? Is there any error message returned by php or mysql?

Categories