For some reason my SQL UPDATE statement is not working.
$con=mysqli_connect("localhost","admin","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$items = array();
$desc = array();
$price = array();
$quantity = array();
$p=0;
while($inventorynumber>$p)
{
$invid[$p] = $_POST['invid'.$p.''];
$items[$p] = $_POST['item'.$p.''];
$desc[$p] = $_POST['desc'.$p.''];
$price[$p] = $_POST['price'.$p.''];
$quantity[$p] = $_POST['quantity'.$p.''];
$sql = "UPDATE `inventory_db` SET `item`='$items[$p]',`description`='$desc[$p]',`quantity`='$quantity[$p]',`price`='$price[$p]' WHERE `invid` = '$invid[$p]'";
$p++;
}
Is there a more efficient way of doing this? Or do I need to add in a mysqli_close($con); after?
I would run the sql query in the loop itself. Unless you're using the array somewhere later, you can simplify this. It's not clear where $inventorynumber is being set. Also, remember to set autocommit.
mysqli_autocommit($con, TRUE);
$p=0;
while($inventorynumber > $p) {
$invid = $_POST['invid'.$p.''];
$item = $_POST['item'.$p.''];
$desc = $_POST['desc'.$p.''];
$price = $_POST['price'.$p.''];
$quantity = $_POST['quantity'.$p.''];
$sql = "UPDATE `inventory_db` SET `item`='$items[$p]',`description`='$desc[$p]',`quantity`='$quantity[$p]',`price`='$price[$p]' WHERE `invid` = '$invid[$p]'";
mysqli_query($conn, $sql);
$p++;
}
mysqli_close($conn);
Related
<?php
include 'dbh.php';
session_start();
if (isset($_GET['gmail'])) {
$gname = $_GET['gmail'];
}
$gname = mysqli_real_escape_string($connect, $gname);
$_SESSION['myusername'] = $gname;
$today = date("d.m.y");
$k=0;
$sql = "SELECT cart_fext FROM cart WHERE cart_sess = '$sess'";
$result=mysqli_query($connect, $sql);
$kode[$k] = array();
$kame[$k] = array();
$kesc[$k] = array();
$kail[$k] = array();
$kid[$k] = array();
$kate[$k] = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
extract($row);
$k = $k + 1;
$cname=$row['cart_item_name'];
$csize=$row['item_size'];
$cdesc=$row['cart_desc'];
$cfpath=$row['cart_fpath'];
$cfext=$row['cart_fext'];
$ccode=$row['cart_itemcode'];
$cuserid=$row['cart_usrid'];
$kode[$k] = $ccode;
$kame[$k] = $cname;
$kesc[$k] = $cdesc;
$kail[$k] = $gname;
$kid[$k] = $cuserid;
$kate[$k] = $today;
}
for($i=1; $i<=$k; $i++) {
$sqlsal = "INSERT INTO sales (s_code, s_name, s_desc, s_mail, s_userid, s_date) VALUES ('$kode[$i]', '$kame[$i]', '$kesc[$i]', '$kail[$i]', '$kid[$i]' ,'$kate[$i]')";
$result=mysqli_query($connect, $sqlsal);
}
header("location:makedir.php");
?>
my table sales is just not accepting data, dbh.php is to connect to the database
I don't understand what is wrong with this script?
please help?
I have checked your insert query it is running fine but I think the problem is with your SELECT query
SELECT cart_fext FROM cart WHERE cart_sess = '$sess'
please print the result of the query. I think that it may not be giving any result.
I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}
i am using the following code to grab some data from a site and store them in a database .
<?php
error_reporting(0);
include("database.php");
$dom = new DOMDocument();
$url = "http://www.kitco.com";
$html = file_get_contents($url);
$dom->loadHTML($html);
$xp = new DOMXPath($dom);
get_live_spot_gold();
get_silver_and_pgm();
function get_live_spot_gold()
{
global $xp;
$live_spot_gold = array();
$bid='000';
$change='000';
$qs = $xp->query('//div[#class="item_border"]/table/tr[#class="alternating"][1]/td[2]');
foreach($qs as $q)
{
$bid = $q->textContent;
break;
}
$qs = $xp->query('//div[#class="item_border"]/table/tr[#class="alternating"][2]/td[2]');
foreach($qs as $q)
{
$change = $q->textContent;
break;
}
//insert into db
echo $bid."<br>";
echo $change."<br>";
$query = "UPDATE live_spot_gold SET _bid = '$bid' , _change = '$change'";
echo $query;
$result = mysql_query($query);
if(!$result)echo "problem in live spot gold"."<br>";
}
function get_silver_and_pgm()
{
global $xp;
$silver_and_pgm = array();
$cnt=0;
$qs = $xp->query('//td[#id="right_column"]/div[#class="item_container"][2]/div[#class="item_border"]/table/tr');
foreach ($qs as $q)
{
$line = $q->nodeValue;
$demo="";
for($i=0;$i<strlen($line);$i++)
{
if($line[$i]==' ')
{
$demo.=' ';
for( ;$line[$i]==' ';$i++);
}
$demo.=$line[$i];
}
$words = explode(" ",$demo);
$silver_and_pgm[$cnt][0]=$words[0]; //metal name
$silver_and_pgm[$cnt][1]=$words[1]; //bid
$silver_and_pgm[$cnt][2]=$words[2]; //change
$cnt++;
}
for($i=0;$i<$cnt;$i++)
{
$metal_name = $silver_and_pgm[$i][0];
$bid = $silver_and_pgm[$i][1];
$change = $silver_and_pgm[$i][2];
//echo "here";
echo $metal_name."<br>";
echo $bid."<br>";
echo $change."<br>";
//$query = "insert into 'silver_and_pgm' values('$metal_name','$bid','$change')";
//$query = "UPDATE silver_and_pgm set _bid='$bid' WHERE _metal_name='$metal_name'";
//$query = "UPDATE silver_and_pgm set _bid = '$bid' WHERE _metal_name = '$metal_name'";
$query = "UPDATE silver_and_pgm set _bid='$bid',_change = '$change' WHERE _metal_name
like'$metal_name%'";
echo $query."<br>";
$result = mysql_query($query);
if(!$result)
echo "problem in silver_and_pgm"."<br>";
}
}
?>
its just working fine in my localhost . but not in my web server . Its grabbing data and storing them in localhost ... no query , no echo statement is working in web server.
would anybody please suggest a way to handle this problem ??
DOM requires PHP 5 (and libxml to be installed). Make sure your server meets the requirements by running php_info(). Also, turn back on your error reporting and see what errors you get.
Script searchs through DB and fix broken links. Search and replace functionality works fine, but when trying to save updated data scripts wrights only first raw. I'm stucked! I can use simple mysql_query commands to update data, but needs PDO...
header('Content-Type: text/html; charset=UTF-8');
error_reporting(E_ALL);
echo "Welcome";
$mysql = new PDO('mysql:host=localhost;dbname=db_name;charset=UTF-8','user','12345');
if (!$mysql) die('Can\'t connect');
$tables = array(
'categories',
'news',
'pages'
);
function getContent($table) {
global $mysql;
$fieldnum = 0;
$fields = array();
$vals = array();
$st = $mysql->query("SHOW FIELDS FROM `{$table}`");
while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
$fields[$fieldnum]=$row["Field"];
$fieldnum++;
}
$totalfields=$fieldnum;
$res = $mysql->query("SELECT * FROM `{$table}`");
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
while ($row = $res->fetch(PDO::FETCH_NUM)) {
for ($j=0; $j<$res->columnCount();$j++) {
$rs = str_replace('index.php/','',$row[$j],$m);
if ($rs && $m>0) {
if ($table == 'categories')
$prim= 'cat_id';
elseif($table == 'news') $prim= 'news_id';
elseif($table == 'pages') $prim= 'page_id';
else $prim= $table.'_id';
$upd = $mysql->prepare($sql);
$update = $upd->execute(array(
':table'=>$table,
':field'=>$fields[$j],
':val'=>$rs,
':idf'=>$prim,
':id'=>$row[0]
));
}
}
}
}
foreach ($tables as $t) {
getContent($t);
}
Need help to fix it!
try to fetch all and then go through array
and you do not need to use prepare every time - just once see Example #2
....
$res = $mysql->query("SELECT * FROM `{$table}`");
$rows = $res->fetchAll(PDO::FETCH_NUM);
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
$upd = $mysql->prepare($sql);
foreach ($rows as $row) {
foreach ($row as $col_name => $value) {
......
prepare outside the loop! you are loosing its value this way, also try $upd->debugDumpParams(); and binding before execution, maybe the values u r binding is not right.
I would appreciate it if anyone willing to tell how to echoing /print.
Below is the process of entering data into the database, before inserting it how can I echoing it to the table?
<?php
session_start();
if(isset($_POST['submit']))
{
include('class/stock_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
?>
Insert this:
echo "<table><tr><th>".implode(array_keys($stocks), '</th><th>')."</th></tr>";
foreach($stocks as $row) echo "<tr><td>".implode('</td><td>', $row)."</tr>";
echo "</table>";
Edit: If printing the data is the goal and the table-view is not important, I recommend print_r($stocks) instead.