PHP multiple forms with multiple queries - php

I have several forms on a page called dispatch.php that each submit PHP code to INSERT into a database table and also UPDATE another database table. The main value that is INSERTED and UPDATED is the bolNum and containerNum.
Note: There can be more than 1 bolNum or containerNum at any time. You'll see the array and how I broke it down.
Here is 1 form (I shortened this as much as possible):
<form action="" method="POST"
id="serviceForm" name="serviceForm">
<label>Container Selected</label>
*** js populates bolNum & containerNum and displays it in these inputs ***
<input type="text" name="containerNum" id="containerNum" class="containerNum" />
<input type="text" name="bolNum" id="bolNum" class="bolNum" />
*** there are more form inputs, I just want to focus on the above 2 ***
<input type="submit" id="modal-form-submit" name="submit" value="Save" />
<?php
if(isset($_POST['submit'])){
$bolArray = explode(',', $_POST['bolNum']);
$containerArray = explode(',', $_POST['containerNum']);
$count = count($bolArray);
for($i = 0; $i < $count; $i++){
$bolService = $bolArray[$i];
$containerService = $containerArray[$i];
*** here is the first query ***
$sqlQuery = "INSERT INTO serviceTable (bol, container)
VALUES ('$bolService', '$containerService')";
*** here is the second query ***
$updateService = "UPDATE dispatchTable SET serviceColumn = 'Y'
WHERE CONTAINER_NUM = '$containerService' AND BOL_NUM = '$bolService'";
$updateServiceQuery = #mysql_query($updateService) or die ('error');
if(mysql_query($sqlQuery)){
$success = true;
}
else{
$success = false;
}
}
}
if($success){
echo "saved";
}
else{
echo "not saved";
}
?>
</form>
Here is another form. Basically, they are both the same, except for the names of the forms, and the names of the queries in the PHP.
<form class="well-small" action="" method="POST"
id="storageForm" name="storageForm">
<label>Container Selected</label>
*** js populates bolNum & containerNum and displays it in these inputs ***
<input type="text" name="containerNum" id="containerNum" class="containerNum" />
<input type="text" name="bolNum" id="bolNum" class="bolNum" />
*** there are more form inputs, I just want to focus on the above 2 ***
<input type="submit" id="modal-form-submit" name="submit" value="Save" />
<?php
if(isset($_POST['submit'])){
$bolArray = explode(',', $_POST['bolNum']);
$containerArray = explode(',', $_POST['containerNum']);
$count = count($bolArray);
for($i = 0; $i < $count; $i++){
$bolStorage = $bolArray[$i];
$containerStorage = $containerArray[$i];
*** here is the first query ***
$sqlQuery = "INSERT INTO storageTable (bol, container)
VALUES ('$bolStorage', '$containerStorage')";
*** here is the second query ***
$updateStorage = "UPDATE dispatchTable SET storageColumn = 'Y'
WHERE CONTAINER_NUM = '$containerStorage' AND BOL_NUM = '$bolStorage'";
$updateStorageQuery = #mysql_query($updateStorage) or die ('error');
if(mysql_query($sqlQuery)){
$success = true;
}
else{
$success = false;
}
}
}
if($success){
echo "saved";
}
else{
echo "not saved";
}
?>
</form>
If you'll notice the 2 queries per form, you will see the INSERT query updates to a different table. Whereas both forms have an UPDATE query that updates the same table, only different columns.
Again, I am having no problem with the INSERT queries. The problem lies with the UPDATE queries. Basically, if you complete the serviceForm, it should update the column in dispatchTable called serviceColumn, which it does. But it also updates the storageColumn which is also in dispatchTable. Vice versa for the completion of the storageForm.
When a form is complete, it should ONLY update the specified column for that form, not both columns for both forms.
I am not sure if it has something to do with the action of the forms being blank. Although I do believe the action may be the key to getting this to work correctly. I am not sure where to start.
Please advise.
* NOTE : I WILL BE USING PDO OR MYSQLI FOR THE NEXT APPLICATION *

Try to rename submit buttons in your forms:
....
<input type="submit" id="modal-form-submit" name="service_submit" value="Save" />
<?php
if(isset($_POST['service_submit'])){
....
and
....
<input type="submit" id="modal-form-submit" name="storage_submit" value="Save" />
<?php
if(isset($_POST['storage_submit'])){
....
Both fields are updated because both parts of PHP code are executed. The reason is you check the same post field $_POST['submit'] that is set when you submit any form on your page.
P.S.
Try to change your queries to make one query instead a lot of queries in a loop. Your application will work faster.
http://dev.mysql.com/doc/refman/5.0/en/update.html
http://dev.mysql.com/doc/refman/5.6/en/insert.html
Your code have one big hole named SQL injection. Try at least to escape values passed in query, even better use parameterized queries: http://php.net/manual/en/pdostatement.bindparam.php

Related

PHP and MYSQLI Check if user ID is present and if not create it

I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}

PHP/MYSQLI simple search not working

I am new to PHP/MYSQLI and I am having trouble creating a simple search to search my database. The columns in my database are: 'ID' , 'Name' , 'Age'. The name of my database is 'users' and the table name is 'employees'.
Here is the code:
<?php require('Connections/Localhost.php'); ?>
<?php
if (isset($_POST['Search'])) {
$search = $_POST['element'];
$sql = mysqli_query("SELECT * FROM employees WHERE Name = '$search' ");
if($sql->num_rows > 0 ) {
while($rows = $sql->fetch_assoc()) {
$id = $rows['ID'];
$name = $rows['Name'];
$age = $rows['Age'];
echo "ID: $id <br> Name: $name <br> Age: $age <br>";
}
}
else {
echo "No Result Found!";
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" name="element" placeholder="Enter A Name"/>
<input type="button" name="Search" value="Search" />
</form>
</body>
</html>
It just returns a blank page and nothing else. I want the user to enter a name in the text area of the form and on clicking the Search button all the data corresponding to that name from the database should be displayed on the webpage. Please correct me where I made the mistake.
You need to change button type to submit.
Your form is not posting.
Change
<input type="button" name="Search" value="Search" />
To:
<input type="submit" name="Search" value="Search" />
Also, mysqli_query() needs database connection resource.
You have given only sql query.
$sql = mysqli_query($databaseConnection, "SELECT * FROM employees WHERE Name = '$search' ");
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
Reference
As per request of OP here I will explain the general concept of a Prepared statement in mysqli feel free to edit this if you feel I did not elaborated on a topic.
The first thing you need to do is prepare the query(preparing the
query is sending an empty query to the database). But instead of
defining the parameter you will put a question mark.
After that you need to bind the parameters to the question marks In the exact order as in the query! The first thing you'll do is defining the type of the parameter string is s integer is i and blob
is b. After that you'll need to define the variables with the data.
And the third and final thing you'll need to do is executing the query. I always use it in an if statement because it will return a
true or false and like this you can check if the query failed or not and handle the error. In this case you will not need an else because the page will die if the query returns false.
/*1.*/
$stmt = $databaseConnection->prepare("SELECT * FROM `employees` WHERE `name` = ?");
/*2.*/
$stmt->bind_param("s",$search);
/*3.*/
if(!$stmt->execute())
{
die("There went something wrong: " . $stmt->error);
}
Edit: here is the question explaining more about how to prevent SQL-injections.

PHP Gallery CMS - Cannot Update Row in PHPMyadmin (LONG)

Project: Create a simple CMS for a photography website. My first project in php. :)
Problem: I am 90% finished with the CMS, but have ran into an issue of not being able to UPDATE row data after being READ from database.
The Goal: What I am trying to achieve seems simple. I have an admin page that reads image data from a database (id, image) and I am using a while loop to display this. It works great, and so does the delete button.
<?php
$query = "SELECT * FROM photos";
$select_all_photos_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_all_photos_query)) {
$photos_id = $row['photos_id'];
$photos_image = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_alt = $row['photos_alt'];
echo "<tr>
<td><input type='checkbox' name='photo' value='photo'></td>
<td><img src='../images/$photos_image' width='70'></td>
<td><a class='edit' href='edit_photo.php?&p_id={$photos_id}'>Edit</a></td>
<td><a onClick=\"javascript: return confirm('Are you sure?') \"class='delete' href='admin.php?delete={$photos_id}'>Delete</a></td>
</tr>";
}
?>
The problem I am having is the Edit Button in my while loop. I am using a get method in my href to get the edit_photo.php page with a parameter named "p_id" that is = to $photos_id.
Once I click the Edit button it sends me to the edit_photo.php page and I see all of the CORRECT information which tells me it is reading it correctly. I do get a error at the bottom ( Notice: Undefined variable: photos_file) See code below.
<?php
if (isset($_GET['p_id'])) {
$photo_id = $_GET['p_id'];
// Send query to photos table in database. //
$query = "SELECT * FROM photos WHERE photos_id = $photo_id";
$result = mysqli_query($connection, $query);
// Grab unique row from photos table in database. //
while($row = mysqli_fetch_assoc($result)) {
$photo_file = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_desc = $row['photos_alt'];
}
}
?>
Now. Here comes the big problem. When I try to update this information, the program busts. I even checked to see if my sql is correct, and if the queries are connecting to database. See code below.
<?php
if (isset($_POST['image'])) {
// After "Save" is pressed, the values white space is trimmed and assigned to a variable. //
$photos_title = trim($_POST['photos-title']);
$photos_desc = trim($_POST['photos-description']);
$photos_file = $_FILES['image']['name'];
$photos_file_temp = $_FILES['image']['name_tmp'];
// The new variables are sanitized. //
$photos_title = mysqli_real_escape_string($connection, $photos_title);
$photos_desc = mysqli_real_escape_string($connection, $photos_desc);
}
// Send the Update query to the database. //
$update_query = " UPDATE photos SET
photos_image = '$photos_file', photos_title = '$photos_title', photos_alt = '$photos_desc'
WHERE photos_id = '$photo_id' ";
// Test the SQL syntax. //
if(!$update_query) {
echo "Wrong." . " " . mysqli_error($connection);
}
else { echo "The SQL appears right..." . "<br>";
}
// Test the Update query. //
$update_result = mysqli_query($connection, $update_query);
if(!$update_result) {
echo "Didnt Connect." . " " . mysqli_error($connection);
} else {
echo "Sent query to to database.";
}
?>
<form action="edit_photo.php" class="settings-form" method="post" enctype="multipart/form-data">
<div class="form-group edit-preview">
<label for="image">Photo</label>
<img src= <?php echo "../images/$photo_file"?> >
<input type="file" name="file_upload">
</div>
<div class="form-group">
<label for="photos-title">Title</label>
<input type="text" name="photos-title" value= <?php echo "$photos_title" ?> class="form-control">
</div>
<div class="form-group">
<label for="photos-description">Description</label>
<textarea type="text" rows="4" name="photos-description" class="form-control" ><?php echo "$photos_desc" ?> </textarea>
</div>
<div class="form-group">
<input type="submit" name="image" class="btn btn-primary" value="Save Photo">
</div>
</form>
I have spent four days trying to figure this out with no luck.
For one thing, it's failing because of this ['name_tmp'].
The syntax is ['tmp_name'] - you had those inversed
Ref: http://php.net/manual/en/features.file-upload.php so your temp file never gets processed.
Then as per your edit and seeing your HTML form:
You're using name="file_upload" and then using the $_FILES['image'] array; those names need to match.
Error reporting would have helped you here.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional note.
If you are attempting to set the given (file) column as binary data instead of the path to the given file(s) as text, then you MUST escape it.
Otherwise, MySQL will throw you an error.
If that is the case, you will need to do the same as the others:
$photos_file = $_FILES['file_upload']['name']; // notice I changed it to what it should be
$photos_file = mysqli_real_escape_string($connection, $photos_file);
as per <input type="file" name="file_upload">
Check for errors against all your queries; you're not doing that in your $query = "SELECT * FROM photos WHERE photos_id = $photo_id"; query.
Add or die(mysqli_error($connection)) to all mysqli_query() should there be an error somewhere.
HTML stickler.
<textarea type="text" - <textarea> does not have a "text" type; remove it.
Footnotes.
If you want to check if your UPDATE truly was successful, use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
Instead of else { echo "The SQL appears right..." . "<br>"; }
As outlined in comments, your code is open an SQL injection.
If $photo_id is an integer, change
$photo_id = $_GET['p_id'];
to
$photo_id = (int)$_GET['p_id'];
However, if that is a string, then you will need to quote it and escape it in your query.

loop to update data coming from form php mysql html

I have the following code that I created to update the database with the data coming from a a php form. $_POST['variables'] are different arrays.
the issue I am having is when I echo $updater the field status and the field display values are not in the correct order. for example if I check the checkbox 3. it will return the value enabled on the first line of the results. any suggestions would help thank you
//update data
$priority = $_POST['priority']; // this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
$position = $_POST['position'];
$widgetid = $_POST['widgetid'];
$display = $_POST['display'];
$i = -1;
foreach($priority as $priori)
{
++$i;
$row_enable = $enable[$i];
$row_height = $height[$i];
$row_prio = $priority[$i];
$positio = $position[$i];
$disp = $display[$i];
$widgeti = $widgetid[$i];
if (isset($enable[$i]))
$enables ="y";
else
$enables ="n";
if (isset($display[$i]))
$displ = "y";
else
$displ = "n";
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
$updater = "UPDATE hpoptions SET position='$positio', height='$row_height', status='$enables', display='$displ', priority='$row_prio' WHERE userid='$ud' and widgetid='$widgeti'";
echo $updater."<br>";
} // ends here
There is no guarantee you will get your arrays in the desired order, unless you force it in the HTML. You probably have something like this:
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w1">
...
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w2">
...
You need to add an extra dimension to the arrays encoded on the field name. You need an unique id for each field group, and I believe your widgetid is exactly that, right? So you can do:
<input type="text" name="data[w1][position]">
<input type="text" name="data[w1][height]"> ...
...
<input type="text" name="data[w2][position]">
<input type="text" name="data[w2][height]"> ...
...
Notice you don't even need a field called widgetid anymore, since the ids will be encoded on every field name. In PHP, you do this to loop through the results:
foreach($_POST['data'] as $widgetid => $data) {
// Make sure to check if the values won't make your SQL query vulnerable to injection!
// http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain
$widgetid = mysql_real_escape_string($widgetid);
$position = is_numeric($data['position']) ? $data['position'] : 0;
// ...
// Build your update query here
}

$_POST not working in PHP

<html>
<head><title>HEllo</title></head>
<body>
<input type="text" name="id">
<input type="text" name="name">
<input type="text" name="address">
<input type ="submit" name = "s" value = "Employee">
<?php
$link =mysql_connect('localhost','root') or die("Failed");
mysql_select_db("gagan",$link) or die("database not exists");
if($_POST['s']=="Employee")
{
print "g";
$id = mysql_real_escape_string($_POST['id']);
$name = $_POST['name'];
$address = $_POST['address'];
print "hi";
$update = "update emp set name = $name, address=$address where id = $id";
$result = mysql_query($update,$link);
print "Hello";
if($result)
{
print "Updated";
}
else{
print "$update";
}
}
?>
</body>
</html>
When i run this code it produce an notice and the above code is not working.
Notice: Undefined index: s in C:\wamp\www\1.php on line 12
What's the problem in my code can anybody tell me?
You forgot the form tag.
<form action="yourform.php" method="POST">
You need to ensure that array member is set first. Try using the result of isset($_POST['s']) to ensure it is set before trying to access it.
You need the form tage with the method set to post.
ie
The main problem (in addition to the missing form tag) is that the program flow continues to the part that tries to save the data even when the form hasn't been submitted yet. You must check that the form has been submitted before trying to save the data, or even easier would be if you moved the data saving part to its own script.
You also have an invalid SQL query but that's another matter :)

Categories