Im tryin to make my update form and query to update by id. But when i put the data in the form he updates all the fields even tho it dont have any data so in the database he get gets "0".
I need to update just the field that have data.
Can you guys help me?
Its giving me always that i have Undefined variables! And only updates the first and second fields!
Thanks, here´s my code:
if (isset($_POST['alterar'])) {
$id_cliente = $_POST["id_cliente"];
$nome_cliente = $_POST["nome_cliente"];
$telefone_cliente = $_POST["telefone_cliente"];
$morada_cliente = $_POST["morada_cliente"];
$email_cliente = $_POST["email_cliente"];
$servico = $_POST["servico"];
$n_pecas = $_POST["n_pecas"];
$tp_arranjo = $_POST["tp_arranjo"];
$descricao = $_POST["descricao"];
}
$query = "UPDATE `clientes` SET ";
if ($nome_cliente) $columns[] = "`nome_cliente` = '{$nome_cliente}'";
if ($telefone_cliente) $columns[] = "`telefone_cliente`= '{$telefone_cliente}'";
if ($morada_cliente) $columns[] = "`morada_cliente` = '{$morada_cliente}'";
if ($email_cliente) $columns[] = "`email_cliente` = '{$email_cliente}'";
if ($servico) $columns[] = "`servico` = '{$servico}'";
if ($n_pecas) $columns[] = "`n_pecas` = '{$n_pecas}'";
if ($tp_arranjo) $columns[] = "`tp_arranjo` = '{$tp_arranjo}'";
if ($descricao) $columns[] = "`descricao` = '{$descricao}'";
$columns = implode(",",$columns);
$query .= $columns . " WHERE id_cliente='$id_cliente'";
mysql_query($query);
?>
You need to change your query to only list columns to be updated if you have values to update them with. This requires building the query string dynamically based on conditions.
Example:
$query = "update `clientes` set ";
if ($nome_cliente) $columns[] = "`nome_cliente`= '{$nome_cliente}'";
if ($telefone_cliente) $columns[] = "`telefone_cliente`= '{$telefone_cliente}'";
//etc..
$columns = implode(",",$columns);
$query .= $columns . " where id_cliente='$id_cliente'";
NOTE: As others have mentioned, this is not secure! You should always sanitize user input before passing it to your database.
Related
I have a PHP/SQL app that processes invoices. Recently, I had an invoice number come in that is not being processed as text, rather as a large exponential number when I do an insert/update on associated SQL tables. For example, take an invoice number that looks like this: 123E456. PHP will try to convert this to an extremely large number due to the 'E' being bookended by numbers.
I am leaning towards this being a PHP issue because when I look at the SQL being sent to the server, it is being scripted without quotes, 123E456 rather than '123E456'.
I have tried multiple ways to try and force it to be text, but nothing seems to work.
If I put single quotes around the string, I get double single quotes in the SQL.
strval() also does not work
the issue might be in the SQL interpreter, but not entirely sure
Right now, I am instructing my clerks to put a space between the E and the numbers, which works for now. But, I am hoping to address this specific issue in the code rather than have the clerk remember to manage it on their end.
Can anyone help with how to force this as being text in the SQL clause?
OK, the code is rather my own style and is based on retrieving a dummy record (the table has 178 columns) and then populating the values into the elements that need updated. It then creates the SQL from the array and does the update. Most of this is just pre-processing to get the values needed. The database being used is Oracle.
function processF0411Z1($id, $user){
include_once $_SERVER['DOCUMENT_ROOT'].'/truck/inc/base.inc.php';
$b = '\' \'';
$z = 0;
$co = get_route_company($id);
$usrsql='SELECT `userID` from `user` where `id` = ' . $user;
$usr = openRecordset_Fetch_Assoc($usrsql);
if($usr[0]==1)$userid = $usr[1]['userID'];
else $userid = $_SESSION['username'];
$jul = date2jul(getdate());
$tjul= getJulTime(getdate());
$sql = "SELECT a.`id`, a.`carrierInvoice`, a.`carrierNbr`, a.`ivd`, a.`dgl`, b.`bol`, b.`obj_acct`, b.`allocation` FROM `route13` a inner join `route131` b on(a.`id` = b.`id`)WHERE a.`id`=".$id;
$myArr = openRecordset_Fetch_Assoc($sql);
if(isset($myArr) && $myArr[0]>0){
$carr = $myArr[1]['carrierNbr'];
$carrsql = 'select `CarrierName` from `Carriers` where `CarrierNbr` = '. $carr;
$carr_res = openRecordset_Fetch_Assoc($carrsql);
if($carr_res[0]==1)$carrName = $carr_res[1]['CarrierName'];
else $carrName = $carr;
// get the next number in the EDI Batch sequence
$nn = getJDEZFileNN();
// get the base associated array of the F0411Z1 table
$msSQL = 'SELECT * FROM PRODDTA.F59411Z1 WHERE VLEDUS=\'TRUCK\' AND VLEDBT=1';
$F0411Z1 = oracle_fetch_array($msSQL);
for($i=1;$i<=$myArr[0];$i++){
// test to see if this record exists
$tsql = "select * from PRODDTA.F0411Z1 where VLEDUS = '".strtoupper($user)."' and VLEDBT = ".$nn[1]['NNN006']." and VLEDLN = " .$i*1000;
$tres = oracle_fetch_array($tsql);
if($tres[0]>0){
$dsql = "delete from PRODDTA.F0411Z1 where VLEDUS = '".strtoupper($user)."' and VLEDBT = ".$nn[1]['NNN006']." and VLEDLN = " .$i*1000;
$count = oracle_update($dsql);
if($count === $tres[0]){
$count = $count;
}
}
$an8_sql = 'SELECT aban85 FROM PRODDTA.F0101 WHERE aban8='.$myArr[$i]['carrierNbr'];
$aban85 = oracle_fetch_array($an8_sql);
$dp = date_parse($myArr[$i]['ivd']);
$dp1 = getDate(mktime(0,0,0,$dp['month'],$dp['day'],$dp['year']));
$ivd = date2jul($dp1);//date('Y-M-d',mktime(0,0,0,$dp['month'],$dp['day'],$dp['year'])));
$dp = date_parse($myArr[$i]['dgl']);
$dp1 = getDate(mktime(0,0,0,$dp['month'],$dp['day'],$dp['year']));
$inv_no = strval($myArr[$i]['carrierInvoice']);
// index: ("VLEDUS", "VLEDBT", "VLEDTN", "VLEDLN")
$gld = date2jul($dp1);//date('Y-M-d',mktime(0,0,0,$dp['month'],$dp['day'],$dp['year'])));
$F0411Z1[1]['VLEDUS'] = '\''.strtoupper($user).'\'';//$_SESSION['userid'];
$F0411Z1[1]['VLEDLN'] = $i*1000;
$F0411Z1[1]['VLEDBT'] = $nn[1]['NNN006'];
$F0411Z1[1]['VLAN8'] = $myArr[$i]['carrierNbr'];
$F0411Z1[1]['VLPYE'] = $aban85[1]['ABAN85'];//$myArr[$i]['carrierNbr'];
$F0411Z1[1]['VLDIVJ'] = $ivd;//$myArr[$i]['ivd'];
//$F0411Z1[1]['VLDSVJ'] = $jul;
$F0411Z1[1]['VLDGJ'] = $gld;
$F0411Z1[1]['VLCO'] = $co;
$F0411Z1[1]['VLKCO'] = $co;
$F0411Z1[1]['VLAG'] = round(($myArr[$i]['allocation']*100),0);
$F0411Z1[1]['VLAAP'] = round(($myArr[$i]['allocation']*100),0);
$F0411Z1[1]['VLVINV'] = $inv_no;// <-- This element is the issue
$F0411Z1[1]['VLRMK'] = (strlen($carrName)>30?substr($carrName,0,29):$carrName);
$F0411Z1[1]['VLGLBA'] = '00573714';
$F0411Z1[1]['VLMCU'] = '1';
$F0411Z1[1]['VLTORG'] = $userid;//$_SESSION['userid'];
$F0411Z1[1]['VLUSER'] = $userid;//$_SESSION['userid'];
$F0411Z1[1]['VLPID'] = 'TRUCK';
$F0411Z1[1]['VLUPMJ'] = $jul;
$F0411Z1[1]['VLUPMT'] = $tjul;
$F0411Z1[1]['VLJOBN'] = 'TRUCK';
$F0411Z1[1]['VLURAB'] = $id;
$F0411Z1[1]['VLURRF'] = $myArr[$i]['bol'];
$z=1;
for($x=1;$x<=$F0411Z1[0];$x++){
$val1 = $F0411Z1[$x];
// first element of array is the counter, skip it
if($val1 != 1){
foreach($F0411Z1[1] as $val){
if($z==1){
$stmt = 'VALUES('.$val;
$z=99;
}
else{
if(!is_numeric($val))$val = '\''.$val.'\'';
$stmt .= ','.$val;
}
}
$stmt .= ')';
//$msSQL = 'INSERT INTO PS_PRODUCTION.PRODDTA.F0411Z1 '.$stmt;
$msSQL = 'INSERT INTO PRODDTA.F0411Z1 '.$stmt;
$count = oracle_update($msSQL);
if($count != 1) return 36;
}
}
}
}
else return 36;
return 0;
}
You can use the strval() method to cast the number as a string.
$number = 123E456;
$string = strval($number);
Or just force it to cast as a string
$string = (string) $number;
I have an intresting question:
I have a form that is send over GET, and i want to secure the database.
Problem is that there are 8 select boxes with arguments that can be passed in the form to the page, but they dont have to be there.
I am currently checking if the select box is sending default value, if its not, im storing it in array. After that i loop trough array and adding the search parameters to string :
$searchString = "WHERE Aktivno = 1";
foreach($pretragaArray as $key => $item){
$searchString = $searchString." AND";
$searchString = $searchString." ". $key ." = " . $item;
}
In the end i end up with search string query like this
WHERE Aktivno = 1 AND IDVrstaOglasa = 1
or
WHERE Aktivno = 1 AND IDOpstina = 15 AND IDGrad = 11 AND IDVrstaOglasa = 1 AND Broj_soba = 3 AND IDKategorijaNekretnine = 5
I am using PDO php class for querying the database.
My question is, is there a way to escape my string that is generated this way, and if not, is there a better way to query the database with dynamic number of atributes in WHERE clause.
You can generate a parameterised query with a dynamic number of parameters like this:
$searchString = "WHERE Aktivno = 1";
$params = array();
$paramNum = 1;
foreach($pretragaArray as $key => $item)
{
$paramName = ':param' . $paramNum++;
$searchString = $searchString." AND";
$searchString = $searchString." ". $key ." = " . $paramName;
$params[$paramName] = $item;
}
$db = new PDO("...");
$statement = $db->prepare("SELECT * FROM some_table " . $searchString);
$statement->execute($params);
$row = $statement->fetch(); // or fetchAll()...
I'm new to PHP and MySQL. I need to fill an array and I want to change the field names and I can't achieve it.
My code:
$querystr = "SELECT DISTINCT descr_bien,ubicacion,marca,modelo,ano,DescrMoneda,valor FROM bienes,Moneda WHERE bienes.IdMoneda = Moneda.IdMoneda AND bienes.Idpropuesta = '" . addslashes($Idpropuesta) . "'";
$result3 = mysql_query($querystr,$dbConn);
while($hrow = mysql_fetch_assoc($result3)){
$descr_bien = $grow['descr_bien'];
$ubicacion = $grow['ubicacion'];
$marca = $grow['marca'];
$modelo = $grow['modelo'];
$ano = $grow['ano'];
$DescrMoneda = $grow['DescrMoneda'];
$valor = number_format($grow['valor'],2,",",".");
$data = array(array('Descripción'=>$descr_bien,'ubicacion'=>$ubicacion,'marca'=>$marca,'modelo'=>$modelo,'Año'=>$ano,'DescrMoneda'=>$DescrMoneda,'valor'=>$valor),array($hrow));
}
$pdf->ezTable($data,$cols,'Bienes:',array('gridlines'=> EZ_GRIDLINE_DEFAULT,'shadeHeadingCol'=>array(0.6,0.6,0.5),'showBgCol'=>1,'width'=>500,'cols'=>array('valor'=>array('justification'=>'right'))));
Okay first of all I am going to assume you have managed to set up $dcConn to get your database connection. If not go look at http://php.net/manual/en/function.mysql-connect.php
Next your while statement is storing each value in $hrow but you seem to be assigning everything to grow.
Your next issue is that $data will be overwritten for every row in your result.
From what I understand you will be wanting something along the lines of
$querystr = "SELECT DISTINCT descr_bien,ubicacion,marca,modelo,ano,DescrMoneda,valor FROM bienes,Moneda WHERE bienes.IdMoneda = Moneda.IdMoneda AND bienes.Idpropuesta = '" . addslashes($Idpropuesta) . "'";
$result3 = mysql_query($querystr,$dbConn);
while($hrow = mysql_fetch_assoc($result3)){
$descr_bien = $hrow['descr_bien'];
$ubicacion = $hrow['ubicacion'];
$marca = $hrow['marca'];
$modelo = $hrow['modelo'];
$ano = $hrow['ano'];
$DescrMoneda = $hrow['DescrMoneda'];
$valor = number_format($grow['valor'],2,",",".");
$data[] = array('Descripción'=>$descr_bien,'ubicacion'=>$ubicacion,'marca'=>$marca,'modelo'=>$modelo,'Año'=>$ano,'DescrMoneda'=>$DescrMoneda,'valor'=>$valor));
}
I do not know about the last line at all so left it out.
One other suggestion that using the PDO library to access the mysql database would usually be a better idea unless this all that the php will ever need to do.
I hope this helps
I built PHP 2 year ago and now i want to change all about database to PDO,i have some problem with update table. I use this function to update table.
public function update($tabel, $fild = null ,$where = null)
{
$update = 'UPDATE '.$tabel.' SET ';
$set=null; $value=null;
foreach($fild as $key => $values)
{
$set .= ', '.$key. ' = :'.$key;
$value .= ', ":'.$key.'":"'.$values.'"';
}
$update .= substr(trim($set),1);
$json = '{'.substr($value,1).'}';
$param = json_decode($json,true);
if($where != null)
{
$update .= ' WHERE '.$where;
}
$query = parent::prepare($update);
$query->execute($param);
$rowcount = $query->rowCount();
return $rowcount;
}
everything work fine using this
$updatefild = array('count' => 20);
$where = "id = '123'";
echo $db->update("mytable",$updatefild, $where);
but i get problem when i want to update row with existing row, in mysql_query I usually use
mysql_query("update mytable set count=count+1 where id='123'");
how i achieve that use PDO ?
thanks
First, why are you using JSON just to decode it into an array? That is confusing.
Secondly, if you were trying to add a number to an existing field, you don't even need prepare().
You could just do
PDO->query("update mytable set count=count+".intval($int)." where id='123'");
If you were doing prepare, you could do:
$stmt = PDO->prepare("update mytable set count=count+:count where id='123'");
$stmt->execute(array(':count' => 1));
or
$stmt = PDO->prepare("update mytable set count=count+? where id='123'");
$stmt->execute(array(1));
Edit: You wouldn't be able to do it with how your function is written as you can't bind column names. PDO will quote it as a standard string. You would have to find a work around, possibly including the =count in the field somehow.
i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.