PHP - Update each row in MySQL table from a web form - php

I populate a web form with rows of data. Some of the fields I need to be updatable so I put the value into a text field. MySQL query is:
SELECT * FROM results WHERE EventID = %s AND CompNo = %s", GetSQLValueString($colname_rsResults, "int"),GetSQLValueString($colname2_rsResults, "int"));
EventID and CompNo are passed in the URL.
Let's say the result is 50 rows. I want to be able to update the Name field (eg, make correction to the spelling), click a button and have the code update the database with any new values. It doesn't matter that most of the values will not change as this is a very infrequent operation.
I used to be able to do this in ASP but I can't seem to do in PHP.
This is the code I am using and I think it is completely wrong!!
if ((isset($_POST["JM_update"])) && ($_POST["JM_update"] == "form1")) {
$i = 0;
$j = $totalRows_rsResults;
while($i < $j)
$resultID=$_GET['ResultID'];
$vDelete=$_GET['Del'];
if ($vDelete == 1) {
$delSQL = sprintf("DELETE FROM Results WHERE ResultID=$resultID");
mysql_query($delSQL,$connFeisResults);
} else {
$name=$_GET['Name'];
$qual=$_GET['Qual'];
$updateSQL = sprintf("UPDATE results SET Name = ".$name{$i}.", Qual = ".$qual[$i]." WHERE ResultID=$resultID");
mysql_query($updateSQL, $connFeisResults);
$i++;
}
}
There is also a checkbox at the end of each row to check if I need that record deleted. That doesn't work either!!
I am using Dreamweaver CS6 and trying to adapt the update behaviours etc.
Any thoughts? Many thanks in advance.

It looks like you're missing an opening brace after your while statement.
--UPDATED
Also, check your sprintf statements -- they look wrong, and they look like they're writing the raw '$resultID' to the SQL String, instead of the value within it.
See how to do it here: http://www.talkphp.com/general/1062-securing-your-mysql-queries-sprintf.html

Related

PHP: Automated data insertion to two connected tables from one form

So, I've been looking for a solution to my case, but I've kept finding only partial and not quite solving-the-matter kind of answers.
First, let me describe what I'm trying to achieve.
In my database I have two tables: PLACES and PLACES_CATEGORIES which are connected by a third table PLACES_A_CATEGORIES in an entity many to many. That is because a PLACE can be characterised by one or more CATEGORIES (but it can also have no CATEGORIES at all).
I want to add data send in one form to two tables: PLACES and PLACES_A_CATEGORIES. The user has all the categories listed with checkboxes and he may (but doesnt have to) check one or more of them.
I automated the display of those checkboxes so it reacts accordingly to changes in database (like adding or removing categories). This part works just fine, but let me show the code for you as it may be useful in solving the real issue:
$query = "SELECT name FROM places_categories";
$result = $connection->query($query);
$category_no = $result->num_rows;
echo "Categories of places:";
for ($j = 0; $j < $category_no; ++$j)
{
$category = $result->fetch_assoc()['name'];
echo '<br><input type="checkbox" id="'.$category.'" name="places_categories" value="'.$category.'"><label for="'.$category.'">'.$category.'</label><br>';
}
So, let's return to the problem. I want to:
always add data (only one row) to the table PLACES
add as many rows of data to the table PLACES_A_CATEGORIES as many checkboxes have been checked
So, let me now show you how I've tried to solve the matter and below I'll explain what and why I've done.
if ($everything_OK==true)//Hurra, everything is ok, lets add the place to the database
{
mysqli_query($connection, "SET NAMES utf8");//need it for special characters
//Adding multiple rows of data to database
$query = "SELECT name FROM places_categories";
$result = $connection->query($query);
$category_no = $result->num_rows;
for ($j = 0; $j < $category_no; ++$j)
{
$category[$j] = $result->fetch_assoc()['name'];
if ($_POST['places_categories'] == $category[$j])
{
//counts number of records in table PLACES
$query1 = "SELECT name FROM places";
$result1 = $connection->query($query1);
$places_no = $result1->num_rows;
$places_no += 1;
//looks for category_id in table places_categories where the name matches the current value from form
$query2 = "SELECT category_id FROM places_categories WHERE name='$category[$j]'";
$result2 = $connection->query($query2);
$what_category_id = mysqli_fetch_array($result2);
$connection->query("INSERT INTO places_a_categories VALUES ('$places_no', '$what_category_id')");
}
}
if ($connection->query("INSERT INTO places VALUES (NULL, 0, 0, 0, '$name', '$wysokosc', '$zajawka', '$zatloczenie', '$data_dodania', '$data_edycji', '$szer_geo', '$dlu_geo', '$tytul', '$opis', '$adres', '$tresc')"))
{
echo "Test!";
}
else
{
throw new Exception($connection->error);
}
}
Okay, explanations:
The part which inserts data to the table PLACES works just fine. It
adds data to the database according to what user has added in a form.
No help needed here.
Because of the before-mentioned automation of
table CATEGORIES I want to check how many of categories actually are
in the database. The first part of the code was supposed to do this.
with instruction FOR I assign every existing category to an array with a value equal to the name of the category in the database
then with instruction IF I want to add ass many rows of data to the table PLACES_A_CATEGORIES as many checkboxes have been checked
first value $places_no equals to id of the place which is being added to another table
second value $what_category_id looks for category_id in table PLACES_CATEGORIES where the name matches the current value got from the checkbox
And what are the results? Data is added to the table PLACES with no problem at all. But there is nothing added to the second table. Furthermore, I get no error message of any kind. It's probably some stupid error I just can't see... Any ideas? What have I done wrong?

PHP MYSQL Check & Append Function

I hope someone can help. Basically I'm fairly OK with PHP and MySQL,
however, I need some advice on how to complete this task.
As my system is to complex to explain, I've condensed it down so it's clearer.
Basically, I have an simple PHP Form that asks the user for their:
Name,Item Ordered, Item Quantity. The OrderID is autogenerated and is a random
4 number. So at the moment I do it with this:
$sql="INSERT INTO system_orders
(orderid,name,itemordered,itemquantity) VALUES
('$randomgeneratednumber', '$_POST[name]','$_POST[itemordered]','$_POST[itemquantity]')"; and
run $sql
Now what I want is if they put the quantity as "2", I want it to create an additional row and append
the randomgeneratednumber. For example, if the randomgeneratednumber was 9876 and the quantity was 2, it would create an additional new row, with the $randomgeneratednumber-2, in this example 9876-2
Would anyone know how to achieve this?
I have temporarily used an if statement (which I know is really bad programming practice)
to append the -2 manually, but there must be a function out there to detect if $quantity = 2
then create additional row with the appended -2 and so on for 3,4,5,6,7,8...
Use a loop:
if ($quantity > 1) {
for ($q = 2; $q <= $quantity; $q++) {
$sql = "INSERT INTO system_orders
(orderid,name,itemordered,itemquantity) VALUES
('$randomgeneratednumber-$q', '$_POST[name]', '$_POST[itemordered]', '$_POST[itemquantity]')";
// run $sql
}
}
You also should switch to a database API that supports parametrized queries, or escape the user-supplied inputs.
$sql="INSERT INTO system_orders
(orderid,name,itemordered,itemquantity) VALUES
('$randomgeneratednumber', '$_POST[name]','$_POST[itemordered]','$_POST[itemquantity]')"; and
run $sql
if ($_POST['itemquantity']>1) {
$multipleorderid = $randomgeneratednumber."-".$POST['itemquantity'];
$sql="INSERT INTO system_orders
(orderid,name,itemordered,itemquantity) VALUES
('$multipleorderid', '$_POST[name]','$_POST[itemordered]','$_POST[itemquantity]')"; and
run $sql
}

php mysql issue with check if record exist before insert

I'm having a little problem with the codes given below. When I'm using the name="staff_number[]" then it insert the record with everything ok even if it is already in the database table and when i use name="staff_number" it does check the record and also give me alert box but when insert the record if it is not in the database it stores only the first number of the staff number like the staff no is 12345 it stores only 1. can anyone help in this record i think there is only a minor issue what I'm not able to sort out.
PHP Code:
<select placeholder='Select' style="width:912px;" name="staff_number[]" multiple />
<?php
$query="SELECT * FROM staff";
$resulti=mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['staff_no']?>"><?php echo $row['staff_name']?></option>
<?php } ?>
</select>
Mysql Code:
$prtCheck = $_POST['staff_number'];
$resultsa = mysql_query("SELECT * FROM staff where staff_no ='$prtCheck' ");
$num_rows = mysql_num_rows($resultsa);
if ($num_rows > 0) {
echo "<script>alert('Staff No $prtCheck Has Already Been Declared As CDP');</script>";
$msg=urlencode("Selected Staff ".$_POST['st_nona']." Already Been Declared As CDP");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Insert Query
$st_nonas = $_POST['st_nona'];
$t_result = $_POST['st_date'];
$p_result = $_POST['remarks'];
$arrayResult = explode(',', $t_result[0]);
$prrayResult = explode(',', $p_result[0]); $arrayStnona = $st_nonas;
$countStnona = count($arrayStnona);
for ($i = 0; $i < $countStnona; $i++) {
$_stnona = $arrayStnona[$i];
$_result = $arrayResult[$i];
$_presult = $prrayResult[$i];
mysql_query("INSERT INTO staff(st_no,date,remarks)
VALUES ('".$_stnona."', '".$_result."', '".$_presult."')");
$msg=urlencode("CDP Staff Has Been Added Successfully");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Your $_POST['staff_number'] is actually an array.
So you have to access it like $_POST['staff_number'][0] here, 0 is a index number.
If the name of select is staff_number[] then $prtCheck will be a array so your check query must be in a loop to make sure your check condition.
if the name is staff_number then the below code is fine.
The answer of amit is right but I will complete it.
Your HTML form give to your PHP an array due to the use of staff_number[] with [] that it seems legit with the "multiple" attribute.
So you have to loop on the given values, you do it with a for and a lot of useless variables without really checking it. From a long time, we have the FOREACH loop structure.
I could help you more if i know what is the 'st_nona', st_date' and 'remarks' values.
According to your question you are getting difficulty in storing the data. This question is related to $_POST array.
Like your question we have selected following ids from the select : 1,2,3,4
It is only storing 1.
This is due to you have not used the loop when inserting the data.
Like below:
<?php
foreach($_POST['staffnumber'] as $staffnumber){
$query=mysql_query("select * from staff where staff_number =".$staffnumber);
if(mysql_num_rows($query)>0){
//action you want to perform
}else{
//action you want to perform like entering records etc. as your wish
}
}
?>
And I would like to suggest you that use the unique keys in database for field and use PHP PDO for database, as it is secure and best for OOPs.
Let me know if you have any queries.

Transform MySQL table and rows

I have one problem here, and I don't even have clue what to Google and how to solve this.
I am making PHP application to export and import data from one MySQL table into another. And I have problem with these tables.
In source table it looks like this:
And my destination table has ID, and pr0, pr1, pr2 as rows. So it looks like this:
Now the problem is the following: If I just copy ( insert every value of 1st table as new row in second) It will have like 20.000 rows, instead of 1000 for example.
Even if I copy every record as new row in second database, is there any way I can fuse rows ? Basically I need to check if value exists in last row with that ID_, if it exist in that row and column (pr2 for example) then insert new row with it, but if last row with same ID_ does not have value in pr2 column, just update that row with value in pr2 column.
I need idea how to do it in PHP or MySQL.
So you got a few Problems:
1) copy the table from SQL to PHP, pay attention to memory usage, run your script with the PHP command Memory_usage(). it will show you that importing SQL Data can be expensive. Look this up. another thing is that PHP DOESNT realese memory on setting new values to array. it will be usefull later on.
2)i didnt understand if the values are unique at the source or should be unique at the destination table.. So i will assume that all the source need to be on the destination as is.
I will also assume that pr = pr0 and quant=pr1.
3) you have missmatch names.. that can also be an issue. would take care of that..also.
4) will use My_sql, as the SQL connector..and $db is connected..
SCRIPT:
<?PHP
$select_sql = "SELECT * FROM Table_source";
$data_source = array();
while($array_data= mysql_fetch_array($select_sql)) {
$data_source[] = $array_data;
$insert_data=array();
}
$bulk =2000;
foreach($data_source as $data){
if(isset($start_query) == false)
{
$start_query = 'REPLACE INTO DEST_TABLE ('ID_','pr0','pr1','pr2')';
}
$insert_data[]=implode(',',$data).',0)';// will set 0 to the
if(count($insert_data) >=$bulk){
$values = implode('),(',$insert_data);
$values = substr(1,2,$values);
$values = ' VALUES '.$values;
$insert_query = $start_query.' '.$values;
$mysqli->query($insert_query);
$insert_data = array();
} //CHECK THE SYNTAX IM NOT SURE OF ALL OF IT MOSTLY THE SQL PART>> SEE THAT THE QUERY IS OK
}
if(count($insert_data) >=$bulk) // IF THERE ARE ANY EXTRA PIECES..
{
$values = implode('),(',$insert_data);
$values = substr(1,2,$values);
$values = ' VALUES '.$values;
$insert_query = $start_query.' '.$values;
$mysqli->query($insert_query);
$insert_data = null;
}
?>
ITs off the top off my head but check this idea and tell me if this work, the bugs night be in small things i forgot with the QUERY structure, print this and PASTE to PHPmyADMIN or you DB query and see its all good, but this concept will sqve a lot of problems..

updaing sql table using UPDATE mysql and php syntax

i am trying to update my records using UPDATE in php and mysql , the query working but there is not updates at all happened on the database , i have many records for tickets which i need to update there status when the user purchase them , let say the user books 10 tickets i used this syntax
for ($counter = 1; $counter <= $tickets; $counter++) {
echo $eventId;
echo $chooseClass;
echo $chooseUser;
$bookTicket = mysql_query("UPDATE units
SET ticketSold = 'Yes',
userIdFK = '$chooseUser'
WHERE BusinessreservationIdFk = '$eventId'
AND classIDfk ='$choosedClass'"
) or die(mysql_error());
if ($bookTicket)
{
echo "<br/>ticket " . $counter . " done !";
}
else
{
i tried to echo all variables here inside the for loop to make sure this for gets all the variables values , which is working , i have like 1000 tickets already stored on mysql table units which i need to update their status from sold = No to Yes. where is the problem here ?
try building the query separately (e.g. $sql = 'UPDATE ...', so you can do an echo $sql and copy/paste the query and run it manually. Nothing in your code looks wrong, so the values you're passing around must not be correct or the WHERE ... logic isn't proper. So run a sample query manually and see if anything happens then.
However, note that you're doing this inside a for() loop, but aren't using that $counter value anywhere. In effect you're just running the SAME query over and over. Setting ticketSold to Yes $counter times isn't going to make it "more" Yes than if you'd done this update only once.

Categories