I have problem in updating the value into my database. The problem here is that the when i am updating the data for all rows, the data from last row will be updated into the first row. Other rows will not be updated including the last row.
Below is my code for updating...
$sql = "SELECT * FROM product where username = '$username'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$rows = mysqli_fetch_array($result);
$id = $rows['pro_id'];
$boxid = $rows['box_id'];
$name = $_POST['pro_name'];
$quan = $_POST['pro_quan'];
$sold = $_POST['pro_sold'];
for ($i = 0; $i < count($_POST['pro_name']); $i++)
{
$sql = "UPDATE product
SET pro_name = '" . $name[$i] . "',
pro_quan = " . $quan[$i] . ",
pro_sold = " . $sold[$i] . "
WHERE pro_id = " . $id . "
AND box_id = '" . $boxid . "' ";
$results=mysqli_query($con, $sql);
}
So, i have no ideas what have gone wrong. Thanks for helping
You need to place the result in a loop.
Something like that:
$sql = "SELECT * FROM product where username = '$username'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while ($rows = mysqli_fetch_array($result))
{
$id = $rows['pro_id'];
$boxid = $rows['box_id'];
$name = $_POST['pro_name'];
$quan = $_POST['pro_quan'];
$sold = $_POST['pro_sold'];
for ($i = 0; $i < count($_POST['pro_name']); $i++)
{
$sql = "UPDATE product
SET pro_name = '" . $name[$i] . "',
pro_quan = " . $quan[$i] . ",
pro_sold = " . $sold[$i] . "
WHERE pro_id = " . $id . "
AND box_id = '" . $boxid . "' ";
$results = mysqli_query($con, $sql);
}
}
I am inserting record from CSV file to MySQL table if any record already exists update that record and insert other records and if there is no match of the record insert all records.
Here is my code
<?php
$connect = mysql_connect('localhost', '', '');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
$cid = mysql_select_db('test', $connect);
define('CSV_PATH', '/home/ubc/Documents/');
$csv_file = CSV_PATH . "test.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['name'] = $csv_array[0];
$insert_csv['email'] = $csv_array[1];
$query = mysql_query("select * from test");
$count = mysql_num_rows($query);
if ($count == 0) {
$query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" . $insert_csv['email'] . "')";
$n = mysql_query($query, $connect);
$i++;
} else {
$query = mysql_query("select name from test where name='" . $insert_csv['name'] . "'");
while ($row = mysql_fetch_array($query)) {
if ($count) {
$sql = "update test set email='" . $insert_csv['email'] . "'";
$qu = mysql_query($sql);
} else {
$query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" . $insert_csv['email'] . "')";
$n = mysql_query($query, $connect);
$i++;
}
}
}
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
<?php
$connect = mysql_connect('localhost', '', '');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
$cid = mysql_select_db('test', $connect);
define('CSV_PATH', '/home/ubc/Documents/');
$csv_file = CSV_PATH . "test.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['name'] = $csv_array[0];
$insert_csv['email'] = $csv_array[1];
$query = mysql_query("select name from test where name='" . $insert_csv['name'] . "'");
$count = mysql_num_rows($query);
if ($count == 0) {
$query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" . $insert_csv['email'] . "')";
$n = mysql_query($query, $connect);
} else {
$sql = "update test set email='" . $insert_csv['email'] . "'";
$qu = mysql_query($sql);
}
$i++;
}
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
Use bellow query..
INSERT INTO table (primkey, col2, col3) VALUES(1, 2, 3) ON DUPLICATE KEY UPDATE
col1=VALUES(1), col2=VALUES(2)
Its example.
This may help you
http://dev.mysql.com/doc/refman/5.0/en/replace.html
I currently have this query that insert data into SQL server. But as the question can contain special characters that include ' which is single quote, it skips my query and did not insert into database.
Any idea what would work for me to be able to insert single quote data into SQL server database?
Example: Trainer's Performance.
Here's my code for inserting data into database:
$sql_array = array();
foreach ($_POST['question'] as $row => $name) {
$question = $name;
$qnsNo = $_POST['qnsNo'][$row];
$input = $_POST['input'][$row];
$options = $_POST['options'][$row];
$others = $_POST['others'][$row];
$compulsory = isset($_POST['compulsory'][$row]) ? $_POST['compulsory'][$row] : "";
$idQuery = "SELECT max(surveyID) FROM scSurveyForm WHERE createBy = '$createBy' AND writeUp = '$writeUp'";
$idResult = sqlsrv_query($conn, $idQuery);
$rows = sqlsrv_fetch_array($idResult);
$lastID = $rows[0];
$sql_array[] = "('" . $question . "'," . $lastID . ",'" . $qnsNo . "','" . $input . "','" . $options . "','" . $others . "','" . $compulsory . "')";
if (!empty($question)) {
$query_single = "INSERT INTO scFormLayout(question, surveyID, qnsNo, input, options, others, compulsory)
VALUES" . implode(', ', $sql_array);
//echo $query_single.'<br/>';
$status = sqlsrv_query($conn, $query_single);
$sql_array = array();
We have a script that generate invoice once a month (cron). But we would like to add feature, that we would be able to select date range "from - to" and then generate invoice only for the date selected.
I guess making input fields with calendar pop-up isn't hard, but filtering with PHP is a bit bigger challenge, so if anyone want to take a look at my code and give me some tips, I would be grateful.
function genInvoice($clientID, $orderID=0, $paid=false)
{
if($orderID == 0)
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and status='closed' and tblusers.clientid=" . $clientID;
else
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and tblusers.clientid=" . $clientID . " and tblorders.id=" . $orderID;
$res = full_query($sql) or die(mysql_error());
// If no closed orders uninvoiced, just return
if(!mysql_num_rows($res))
return 0;
$amount = 0;
$orders = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
// print_r($row);
// print "<br><hr>";
$amount += $row['amount'];
$orders[] = $row['id'];
}
$date = date("Y-m-d");
$status = $paid ?'Paid' : 'Unpaid';
$sql = "insert into tblinvoices (clientid, date, duedate, subtotal, total, status) values (" . $clientID . ",'" . $date .
"','" . $date . "'," . $amount . "," . $amount . ",'" . $status . "')";
$res = full_query($sql) or die(mysql_error());
$invoiceid = mysql_insert_id();
$sql = "update tblorders set invoiceid=" . $invoiceid . " where id in (" . implode(",", $orders) . ")";
$res = full_query($sql) or die(mysql_error());
$sql = "select tblorders.id as ReportID, FirstName, LastName, SearchName, CountyID, StateID, bl_orderitems.userid, bl_orderitems.amount, " .
"bl_orderitems.notes from tblorders, bl_orderitems left join bl_search on bl_search.id=packageid where tblorders.id in (" .
implode(",", $orders) . ") and bl_orderitems.orderid=tblorders.id order by tblorders.id,bl_orderitems.id";
$res = full_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
if($row['CountyID'] != 0)
$locale = getCounty($row['CountyID']);
else if($row['StateID'] != 0)
$locale = getState($row['StateID']);
if($row['SearchName'] != "")
$description = mysql_real_escape_string($row['FirstName'] . " " . $row['LastName'] . " " .
$row['SearchName'] . " " . $locale . " (Order #" . $row['ReportID'] . ")");
else
$description = "Search Package: " . mysql_real_escape_string($row['notes'] . " (Order #" . $row['ReportID'] . ")");
$sql = "insert into tblinvoiceitems (invoiceid, userid, type, description, amount, duedate) values " .
"(" . $invoiceid . "," . $row['userid'] . ",'search','" . $description . "','" .
$row['amount'] . "','" . $date . "')";
// print $sql . "<br>";
full_query($sql) or die(mysql_error());
}
sendmessage ('Invoice Created', $invoiceid);
return $invoiceid;
}
not going to look through all that code, but filtering results by a date range is easy.
SELECT id FROM some_table WHERE some_date_field BETWEEN $first_date AND $second_date
I have written a page that will scan a site and then extract certain code from the source. That part is working successfully, however I want to run this over multiple pages and dump the details into a database. I am stuggling to get the loop working, this is what I currently have:
date_default_timezone_set("australia/sydney");
$host = 'http://www.tabonline.com.au/';
$day = date(d);
$month = date(m);
$year = date(Y);
$slash = '/';
$mtgraces = '/mtgraces.html';
//Gallops Meetings on Todays racing page
$content = file_get_contents($host . $year . "/". $month . "/" . $day . $mtgraces);
preg_match_all('#<a[^<>]+href\s*=\s*[\'"](.R[0-9]+.html*)[\'"]#i', $content, $matches);
foreach ($matches[1] as $url) $links[] = "$host$year$slash$month$slash$day$slash$url";
//get the runners from each page
for($c=0; $c<count($links); $c++)
$racepage = file_get_contents($links[$i]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode = explode(",", $dblocationcode);
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
{
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
At the moment the output for this is giving me the correct contents of the last page in the list of sites (the $links variable). Ultimately I want it to loop through the whole $links variable and then import that data, using the $query variable, into a database so I can do further analysis on it.
I hope this makes sense and you can see the error in my ways.
Hmm... There are a few issues in here...
for($c=0; $c<count($links); $c++)
This loop is executing just the next line:
$racepage = file_get_contents($links[$i]);
However, $i isn't defined, I suspect you want $c. Also, you need to place some braces around various parts... Now, this is untested, but I think you want something like:
date_default_timezone_set("australia/sydney");
$host = 'http://www.tabonline.com.au/';
$day = date(d);
$month = date(m);
$year = date(Y);
$slash = '/';
$mtgraces = '/mtgraces.html';
//Gallops Meetings on Todays racing page
$content = file_get_contents($host . $year . "/". $month . "/" . $day . $mtgraces);
preg_match_all('#<a[^<>]+href\s*=\s*[\'"](.R[0-9]+.html*)[\'"]#i', $content, $matches);
foreach ($matches[1] as $url) $links[] = "$host$year$slash$month$slash$day$slash$url";
//get the runners from each page
$final_number = array();
$final_rating = array();
$final_location = array();
$final_locationcode = array();
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number[] = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating[] = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location[] = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode[] = explode(",", $dblocationcode);
}
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
if(count($queries) != 0)
{
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
}
$final_number is something you get from a racepage link right? You are using it to as $i<count($final_number). Instead i think you should use $i<count($links) there as what you want to insert is a row for each link. What you can do is move the:
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
...line to the bottom of for($c=0; $c<count($links); $c++) line which would make you code look like this starting from that point, (notice $data=array() is defined before the loop):
$data = array();
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number[] = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating[] = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location[] = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode[] = explode(",", $dblocationcode);
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[0] . "', '" . $final_rating[0] . "')";
}
if(count($queries) != 0)
{
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
}
I think there are some problems with this code still.
Edit:I also noticed that on this line
$number_data = implode(",", $number[0]);
Wouldn't $number[0] be a string, it couldn't be an array because $number is an array of matched strings so $number[0] would be the whole matched string. This would apply to 'number_data', 'rating_data', 'location_data' and 'locationcode_data' so you can
$number_data = strip_tags($number[0]);
and then when creating the insert data:
$data[] = "('" . $final_location . "', '" . $final_locationcode . "', '" . $final_number . "', '" . $final_rating . "')";
I have managed to figure it out!
I needed to put the whole lot in the for loop, so it looks like this:
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode = explode(",", $dblocationcode);
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
{
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%HOSTNAME"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password%"; // the password specified when setting-up the database
$database = "%database%"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error());
}
Thank you all for your help, it seems like a great community that is here. I am sure to keep an eye on it for more fixes.