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 want to UPDATE a row in a table or INSERT it if it doesn't exist?
I have already read solution from this link. How do I UPDATE a row in a table or INSERT it if it doesn't exist?
So, i used replace but it did not work. It only added new row into the table but did not update anything.
this is my structure
<?php
define('ROOTPATH', __DIR__);
$output = [];
$output['result'] = [];
$output['image_path'] = [];
$applicationName = (isset($_POST) && array_key_exists('applicationName', $_POST)) ? $_POST['applicationName'] : 'applicationName';
if (empty($applicationName)) {
$output['result'][] = 'missing application name';
}
else if (is_array($_FILES) && array_key_exists('image', $_FILES) && array_key_exists('logo', $_FILES))
{
$upload_dir = '/upload_dir/';
$upload_path = ROOTPATH . $upload_dir;
$applicationName = $_POST['applicationName'];
$sql_field_list = ['applicationName'];
$sql_value_list = [$applicationName];
foreach ( $_FILES as $key => $upload) {
if($key != 'image' && $key != 'logo')
{
$output['result'][] = $key . ' is invalid image';
}
else
{
if ($upload['error'] == UPLOAD_ERR_OK &&
preg_match('#^image\/(png|jpg|jpeg|gif)$#', strtolower($upload['type'])) && //ensure mime-type is image
preg_match('#.(png|jpg|jpeg|gif)$#', strtolower($upload['name'])) ) //ensure name ends in trusted extension
{
$parts = explode('/', $upload['tmp_name']);
$tmpName = array_pop($parts);
$fieldname = ($key == 'image') ? 'bgBNPage' : 'logo';
$filename = $applicationName . '_' . $fieldname . '.' . pathinfo($upload["name"], PATHINFO_EXTENSION);
if (move_uploaded_file($upload["tmp_name"], $upload_path . $filename))
{
$sql_field_list[] = $fieldname;
$sql_value_list[] = $upload_dir . $filename;
$output['image_path'][$key] = $upload_dir . $filename;
}
else
{
$output['result'][] = $key . ' upload fail';
}
}
else
{
$output['result'][] = $key . ' error while upload';
}
}
}
//after upload complete insert pic data into database
$con = mysqli_connect("localhost", "root", "root", "museum");
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$fields = implode(', ', $sql_field_list);
$values = implode("', '", $sql_value_list);
$sql = "REPLACE INTO general (" . $fields . ") VALUES ('" . $values . "');";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
} else {
$output['result'][] = 'no file selected';
}
header('Content-type: application/json');
echo json_encode($output);
echo json_encode('finish');
?>
Can i use
if(logo or bgBNPage is enpty)
{
insert into database
}
else{
Update database
}
please tell me the correct syntax.
I'm guessing username is the field where, if it's a duplicate, you want to update. So, if username is a unique key, you can do something like:
insert into general ([fields]) values ([values])
on duplicate username update
[whatever]
I found the solution.
I use if else condition to proove it.
This is my code result
//after upload complete insert pic data into database
$con = mysqli_connect("localhost", "root", "root", "museum");
$sql = "SELECT logo,bgBNPage FROM general ";
$result = mysqli_query($con, $sql);
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$fields = implode(', ', $sql_field_list);
$values = implode("', '", $sql_value_list);
if(mysqli_num_rows($result) > 0)
{
$str_array = [];
for($i =0; $i < count($sql_field_list); $i++)
{
$str_array[] = $sql_field_list[$i] . "='" . $sql_value_list[$i] ."'";
}
$sql = 'UPDATE general SET ' . implode(',', $str_array);
//$sql = "UPDATE general SET (" . $fields . ") = ('" . $values . "');";
}
else
{
$sql = "INSERT INTO general (" . $fields . ") VALUES ('" . $values . "');";
}
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
$objetos = json_decode($_POST['objetos']);
$query1 = "DELETE FROM `usuarioObjeto` WHERE idusuario=" . $id . "";
$result1 = mysqli_query($conn, $query1) or die('Consulta fallida: ' . mysqli_error());
$size = count($objetos); //this works
//this do not insert into the BD
for ($k = 0; $k < $size; $k++) {
$ido = intval($objetos[$k]['id']);
$cantidad = intval($objetos[$k]['cantidad']);
$query2 = "INSERT INTO `usuarioObjeto`( `idUsuario`, `idObjeto`, `cantidad`) VALUES (" . $id . "," . $ido . "," . $cantidad . ")";
$result2 = mysqli_query($conn, $query2) or die('Consulta fallida: ' . mysqli_error());
}
thanks
and i have tried to access to one property like this but nothing
$ido = intval($objetos[0]['id']);
json_decode($_POST['objetos']); replece to json_decode($_POST['objetos'],true);
By adding true as a second parameter, it will convert your json to array
More information: json_decode
Use this code :
$objetos = json_decode($_POST['objetos'],true);
I have a csv upload plugin for wordpress. I can upload the files on a mac but on a windows pc it fails to upload. The csv files are created on the pc with utf-8 encoding.
if (isset($_POST) && !empty($_POST)) {
if (isset($_FILES) && $_FILES['csv_file']['size'] > 0 && $_FILES['csv_file']['type'] === 'text/csv') {
global $wpdb;
ini_set("auto_detect_line_endings", true);
$start_row = (int) $_POST['start_row'];
/*
* Get CSV data and put it into an array
*/
$fileData = file_get_contents($_FILES['csv_file']['tmp_name']);
$lines = explode(PHP_EOL, $fileData);
$csv = array();
foreach ($lines as $line) {
$csv[] = str_getcsv($line);
}
/*
* Put each row into the database
*/
$x = 1;
$insert_count = 0;
$insert_output = array();
$wpdb->query('TRUNCATE TABLE table');
foreach ($csv as $data) {
if ($x >= $start_row) {
$date = fix_date($data[0]);
$sql = "
INSERT INTO table ( date, column_1, column_2, column_3, column_4, column_5, column_6, column_7 )
VALUES ( '" . $date . "', '" . addslashes( $data[1] ) . "', '" . utf8_encode( $data[2] ) . "', '" . addslashes( $data[3]) . "', '" . $data[4] . "', '" . addslashes( $data[5] ) . "', '" . $data[6] . "', '" . $data[7] . "' )
";
$wpdb->query($sql)/* or die($sql)*/;
$insert_output[] = $insert_count . '. Added: ' . $data[1] . ' - ' . $data[3] . '<br />';
$insert_count++;
}
$x++;
}
echo '<div class="csv_success">Success. ' . number_format($insert_count) . ' rows uploaded.</div>';
} else {
echo '<div class="csv_failure">Please make sure the file you uploaded is a CSV.</div>';
}
}
Any ideas how I can get this to work on windows and mac?
Cheers
<?php
ini_set('max_execution_time', 0);
$con = mysql_connect("localhost", "", "") or die("not connect");
mysql_select_db("demo") or die("select db");
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
//Set path to CSV file
$csvFile = 'page.csv';
$csv = readCSV($csvFile);
//echo count($csv);
for ($i=1; $i <count($csv) ; $i++) {
$sql="insert into demo1 (name,bdate,phonenumber ) values('".$csv[$i][0]."','".$csv[$i][1]."' ,'".$csv[$i][2]."')";
mysql_query($sql);
}
echo 'done';
?>
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.