php mysql bulk records update? - php

I'm trying to update multiple mysql records, with this code:
<strong>Update multiple rows in mysql</strong><br>
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
// Count table rows
$count=mysql_num_rows($result);
?>
<table width="500" border="0" cellspacing="1" cellpadding="0">
<form name="form1" method="post" action="">
<tr>
<td>
<table width="500" border="0" cellspacing="1" cellpadding="0">
<tr>
<td align="center"><strong>Id</strong></td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Lastname</strong></td>
<td align="center"><strong>Email</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center"><? $id[]=$rows['id']; ?><? echo $rows['id']; ?></td>
<td align="center"><input name="name[]" type="text" id="name" value="<? echo $rows['name']; ?>"></td>
<td align="center"><input name="lastname[]" type="text" id="lastname" value="<? echo $rows['lastname']; ?>"></td>
<td align="center"><input name="email[]" type="text" id="email" value="<? echo $rows['email']; ?>"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</form>
</table>
<?php
// Check if button name "Submit" is active, do this
if($Submit){
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name
SET name='$name[$i]',
lastname='$lastname[$i]',
email='$email[$i]'
WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}
if($result1){
header("location:update_multiple.php");
?>
It shows records from the DB in input text boxes, but when I change old records with new ones and then submit, nothing happens, page refreshes with old values.

You will need to check if the form is submitted using $_POST['Submit'].
Also you could use a hidden input field to keep track of each row to update:
<input type="hidden" name="id[]" value="<?php echo $row['id']; ?>" />
Then when handling your submission you should do something like this:
if(isset($_POST['Submit'])) {
$ids = $_POST['id'];
$names = $_POST['name'];
$lastnames = $_POST['lastname'];
$emails = $_POST['email'];
//
foreach($ids as $id) {
// update the record based on the id and supplied data
}
}
And of course the update process should be executed before you retrieve you rows from the database. In other words the above code should be placed near the top of your script. At least before the:
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);

Submit should define that form if sent
move update code before select because you first view, and just after that update info, so you'll view previous results all the time
...
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if($Submit){
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET name='$name[$i]', lastname='$lastname[$i]', email='$email[$i]' WHERE id='$id[$i]'";
$result1=mysql_query($sql1
);
}
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
// Count table rows
...

Using if($Submit){ is not the correct way to determinate if a form has been submitted ...
you should use :
if($_SERVER['REQUEST_METHOD'] == "POST")
then process your submitted values.
Note : you should update the DB before showing the values ....
And please make sure you read about SQL Injection

First of all mysql_query() doesn't return anything when you execute an update command.
You could use instead mysql_affected_rows to retrieve the number of rows changed by the previous query:
http://php.net/manual/en/function.mysql-affected-rows.php
Then, you should also do some refactoring like moving the update code before displaying the results, otherwise the header location directive won't work if you already sent output to the browser.

did you apply the varaible names in single code?
$sql1="UPDATE $tbl_name SET name='$name[$i]', lastname='$lastname[$i]', email='$email[$i]' WHERE id='$id[$i]'";
change above query to
$sql1="UPDATE $tbl_name SET name='".$name[$i]."', lastname='".$lastname[$i]."', email='".$email[$i]."' WHERE id=$id[$i]";

Related

mysql / php: Update multiple rows

I try to use the below code to update multiple rows, the below code can view the results of rows but it can not be updated, where is wrong place? How to modify it ?
<?php
$host="localhost"; // Host name
$username="abc"; // Mysql username
$password="abc123"; // Mysql password
$db_name="abc"; // Database name
$tbl_name="BRAddress"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("Cannot connect");
mysql_select_db("$db_name")or die("Cannot select Database");
$sql="SELECT * FROM $tbl_name WHERE br_no='62779457'";
$result=mysql_query($sql);
// Count table rows
$count=mysql_num_rows($result);
?>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<form name="form1" method="post" action="">
<tr>
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td align="center"><strong>BR No.</strong></td>
<td align="center"><strong>Date of Register</strong></td>
<td align="center"><strong>Address</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center">
<? $br_no[]=$rows['br_no']; ?><? echo $rows['br_no']; ?>
</td>
<td align="center">
<input name="br_date_of_register[]" type="date" id="br_date_of_register" value="<? echo $rows['br_date_of_register']; ?>">
</td>
<td align="center">
<input name="br_address[]" type="text" size="60" id="br_address" value="<? echo $rows['br_address']; ?>">
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</form>
</table>
<?php
// Check if button name "Submit" is active, do this
if($Submit){
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET
br_date_of_register='$br_date_of_register[$i]',
br_address='$br_address[$i]'
WHERE br_no='$br_no[$i]'";
$result1=mysql_query($sql1);
}
}
if($result1){
header("location:update_sample.php");
}
mysql_close();
?>
Thank you very much for your help & support !
I think that you need to change this part
if($Submit){
to
if($_POST('Submit')){
I haven't run the whole or looked at entire code, but you have nothing that defines $Submit variable though from what I see.
Or you can put in
$Submit = $_POST('Submit');
before the if statement.
Let me know how you go.
Cheers
Your POST variable are empty. $br_date_of_register has no value. You must use this like following
$br_date_of_register = $_POST[br_date_of_register];
$br_address = $_POST[br_address];
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET
br_date_of_register='$br_date_of_register[$i]',
br_address='$br_address[$i]'
WHERE br_no='$br_no[$i]'";
$result1=mysql_query($sql1);
}
Edit
if($Submit)
To
if($_SERVER['REQUEST_METHOD'] == "POST")
Considering your Submit check,
you can use this,
if(isset($_POST["Submit"]))
{
}
Further in your SQL statement, do this,
$sql1='UPDATE ' . $tbl_name . ' SET
br_date_of_register = ' . $br_date_of_register[$i] .
' , br_address = ' . $br_address[$i] .
' WHERE br_no = ' . $br_no[$i];

How to update points by adding previous points and current points

How do I update my php/mysql by adding the previous vote and new vote
for example, in mysql. the vote point is 25. when I entered again with 25points. it became 50points. this is the scenario. I have table name"subj_eva" with coloumn of id, facultyname and totalvotes. how do I update my totalvotes by adding the old points and new points?
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="password"; // Mysql password
$db_name="ramon_pascual"; // Database name
$tbl_name="subj_eva"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$profname=$_POST['profname'];
$votecount=$_POST['votecount'];
$subj=$_POST['subject'];
// Insert data into mysql
$sql = "UPDATE $tbl_name SET facultyname='$profname', totalvotes='$votecount', subjects='$subj'";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='indextest.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
and this is my html code
<html>
<head><title> index test</title></head>
<body>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form1" method="post" action="welcome.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td colspan="3"><strong>Insert Data Into mySQL Database </strong></td>
</tr>
<tr>
<td width="71">Professor Name</td>
<td width="6">:</td>
<td width="301"><input name="profname" type="text" id="profname"></td>
</tr>
<tr>
<td>vote count</td>
<td>:</td>
<td><input name="votecount" type="text" id="votecount"></td>
</tr>
<tr>
<td>subject</td>
<td>:</td>
<td><input name="subject" type="text" id="subject"></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
You can modify your query to add the new value to the current value. I recommend converting votecount to an integer beforehand.
$votecount = intval($votecount);
$sql = "UPDATE $tbl_name SET facultyname='$profname', totalvotes=totalvotes + $votecount, subjects='$subj'";
Try:
$sql = "UPDATE $tbl_name SET facultyname='$profname', totalvotes=totalvotes + '$votecount', subjects='$subj'";
I do not understand what you want, but is always use in the transmission function mysql_real_escape_string() database any string variables! Otherwise possible Mysql injections. And in double quotes variables highlight the brackets {}, otherwise the function will give the database is not the variable.
Try this..
$votecount=$_POST['votecount'];
$getprevious =mysql_fetch_array(mysql_query("select * from $tbl_name order by id desc"));
$previouspoint= $getprevious[0]['totalvotes'];
$votecount = intval($previouspoint) + intval($votecount);
$sql = "UPDATE $tbl_name SET facultyname='$profname', totalvotes='$votecount', subjects='$subj'";
$result=mysql_query($sql);
try using like this
$query="update table_name set 'totalvotes'=(select `totalvotes` from `table_name` where id='".$id."')+'".$current_count."' where id='".$id."' ";

PHP/MySQL Table Update Issue

I have a MySQL Database setup with a bunch of usernames, passwords, and other details. I have one "administrator" section on the site that I want to be able to edit the users information when needed.
So far I have a page called president_admin.php (code below), which displays a table with the name, username, and password of the user, as well as a link to update the user. I have the table working correctly, it displays the information and all. The update link, takes the users ID in the table, then sends it to a page called StudentEdit.php (code below) which then retrieves the ID of the User, and fills three text fields with the username, password, and name just fine. It works.
So I fill out the fields to test and see if it will let me update the variables in the database, and press submit which goes to a page called StudentUpdate.php (code below). The page connects to the database, and uses and if to display and error if it will not update. It goes through fine and says it successfully update.... But it indeed does not. Can someone look at my code and help me out.
I've been stuck on this for hours. Please Note this is a code snip, its actually secured and has more to the page. Also I'm a teen trying my best here... Sorry if this is scrutiny to the coding world.
president_admin.php
<?php
session_start();
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="100%" border="1" cellspacing="0" cellpadding="3">
<tr>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Username</strong></td>
<td align="center"><strong>Password</strong></td>
<td align="center"><strong>Update</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['name']; ?></td>
<td><? echo $rows['username']; ?></td>
<td><? echo $rows['password']; ?></td>
<td align="center">Update</td>
</tr>
<?php
}
?>
<?php
mysql_close();
?>
</table>
</td>
</tr>
</table>
StudentEdit.php
<?php
session_start();
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<form name="form1" method="post" action="StudentUpdate.php">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Username</strong></td>
<td align="center"><strong>Password</strong></td>
</tr>
<tr>
<td> </td>
<td align="center">
<input name="name" type="text" id="name" value="<? echo $rows['name']; ?>">
</td>
<td align="center">
<input name="username" type="text" id="username" value="<? echo $rows['username']; ?>" size="15">
</td>
<td>
<input name="password" type="text" id="password" value="<? echo $rows['password']; ?>" size="15">
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</td>
<td> </td>
</tr>
</table>
</td>
</form>
</tr>
</table><?php
// close connection
mysql_close();
?>
StudentUpdate.php
<?php
session_start();
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE members SET name='$name', username='$username', password='$password' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successfully Updated";
echo "<BR>";
echo "<a href='president_admin.php'>Return to dashboard</a>";
}
else {
echo "Error, something went wrong.";
}
?>
add this to your studentupdate.php
if($_POST['Submit']))
{
$name=$_POST['name'];
$username=$_POST['username'];
$password=$_POST['password'];
$id=$_POST['id'];
//your script
}
and also change the variable name in connection script
$username=""; // Mysql username
$password="";

InPHP,MySQL, how do i update a row in a table using HTML form

I have 2 PHP files for this. The first one update.php contains the user form to update the row. The next one,update_ac contains the coding to carry out this update. The problem is i do not get a proper output
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "yumyum"; // Database name
$tbl_name = "food"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
// get value of id that sent from address bar
//$id=$_GET['id'];
$id = $_REQUEST['id'];
// Retrieve data from database
$sql = "SELECT * FROM $tbl_name WHERE id='$id'";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<form name="form1" method="post" action="update_ac.php">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td align="center"><strong>name</strong></td>
<td align="center"><strong>price</strong></td>
<td align="center"><strong>Quantity</strong></td>
</tr>
<td align="center">
<input name="name" type="text" id="name" value="<? echo $line['name']; ?>">
</td>
<td align="center">
<input name="price" type="text" id="price" value="<? echo $line['price']; ?>" size="15">
</td>
<td align="center">
<input name="Quantity" type="text" id="Quantity" value="<? echo $line['Quantity']; ?>" size="15">
</td>
<td>
<input name="id" type="hidden" id="id" value="<? echo $line['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?php
// close connection
mysql_close();
?>
**This is update_ac.php**
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="yumyum"; // Database name
$tbl_name="food"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE $tbl_name SET name='$name', price='$price', Quantity='$Quantity' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='yumhome.php'>View result</a>";
}
else {
echo "ERROR";
}
?>
At First
change the variable $lines to $rows
Then in update_ac.php
get all the value using $_POST[];
because in form method="post"

Using a MySQL table-populated PHP dropdown to insert selection into another table

I'm making a web app to help determine whose turn it is to make tea in my office, giving me a focus to learn the use of PHP/MySQL. Apologies for newbie ignorance.
For new users signing up I need to populate the user table with their selections from a dropdown, which is itself populated from a separate table. So when a user signs up, I wan them to select the name of their favourite drink from the dropdown/drinks table and I want the ID of that drink saved in the defaultdrink field of the user table. I also understand this should be done using POST, not GET.
Have so far successfully made a form that populates the DB and have made a dropdown populated from the DB - but no success yet in doing both.
The form page is...
<?php
require "insert_dropdown.php";
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form1" method="post" action="insert_ac.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td colspan="3"><strong>Sign up to the Tea App</strong></td>
</tr>
<tr>
<td width="71">Name</td>
<td width="6">:</td>
<td width="301"><input name="name" type="text" id="name"></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<?php
$dropdown = "<select name='drinkname'>";
while($row = mysql_fetch_assoc($dresult)) {
$dropdown .= "\r\n<option value='{$row['drinkname']}'>{$row['drinkname']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
The form actions are led by insert_ac.php...
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="tea"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$name=$_POST['name'];
$pref=$_POST['pref']; // Drink preference
// Insert data into mysql
$sql="INSERT INTO $tbl_name(name, pref)VALUES('$name', '$pref')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
}
else {
echo "ERROR";
}
// close connection
mysql_close();
?>
And I'm populating the dropdown using insert_dropdown.php...
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Write out our query.
$dquery = "SELECT drinkname FROM drinks";
// Execute it, or return the error message if there's a problem.
$dresult = mysql_query($dquery) or die(mysql_error());
// if successfully insert data into database, displays message "Successful".
if($dresult){
echo "Drink Successful";
echo "<BR />";
}
else {
echo "ERROR";
}
// close connection
mysql_close();
?>
Am I beyond saving?
Cheers,
Alex
Do not close mysql connection.
Or - even better - store the actual db rows into array and use that array to populate drop-down.
and put your select box inside of the form.
Well if you want yo learn something useful yet simple
config.php
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="tea"; // Database name
// Connect to server and select database.
mysql_connect($host, $username, $password);
mysql_select_db($db_name);
// A function! greatest invention since wheel.
function dbgetarr($query){
$a = array();
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
main page.
<?php
include 'config.php';
$data = dbGetArr("SELECT drinkname FROM drinks");
$tpl = 'tea.tpl.php';
include 'main.tpl.php';
main site template main.tpl.php
<html>
<body>
<?php include $tpl ?>
</body>
</html>
tea page template tea.tpl.php
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form1" method="post" action="insert_ac.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td colspan="3"><strong>Sign up to the Tea App</strong></td>
</tr>
<tr>
<td width="71">Name</td>
<td width="6">:</td>
<td width="301"><input name="name" type="text" id="name"></td>
</tr>
<tr>
<td width="71">Name</td>
<td width="6">:</td>
<td width="301"><input name="drink" type="text" id="name">
<select name="drinkname">
<?php foreach($data as $row)): ?>
<option value="<?=$row['drinkname']?>"><?=$row['drinkname']?></option>
<?php endforeach ?>
</select>
</td>
</tr>
<tr>
<td colspan="3" align="center">
<input type="submit" name="Submit" value="Submit">
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
insert_ac.php
<?php
include 'config.php';
$tbl_name="users"; // Table name
// Get values from form and formatting them as SQL strings
$name = mysql_real_escape_string($_POST['name']);
$pref = mysql_real_escape_string($_POST['pref']); // Drink preference
// Insert data into mysql
$sql="INSERT INTO `$tbl_name` (name, pref) VALUES('$name', '$pref')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
}else {
echo "ERROR";
}

Categories