transform sql query to Fluentpdo query - php

i have this sql query written in php:
$query = sprintf("UPDATE bank_info SET
amount_dollar = amount_dollar +'$amount_dollar' ,
amount_euro = amount_euro + '$amount_euro' ,
amount_local = amount_local + '$amount_local'
WHERE bank_id = '$bank_id' ");
this query works fine, but i want to transform this query using FluentPDO.
i want to use arrays to SET the values .
for example:
$table='bank_info'; //table name
$arrVal=array(); //values needs to be SET
$arrVal['amount_dollar = amount_dollar+?']=$amount_dollar;
$arrVal['amount_euro = amount_euro+?']=$amount_euro;
$arrVal['amount_local = amount_local+?']=$amount_local;
$arrWhere=array(); //where condition
$arrWhere['bank_id']=$bank_id;
this is the query:
$query = $this->pdo->update($table)->set($arrVal)->where($arrWhere);
$query->execute();
I think the problem is in the $arrVal, cant find the proper way to SET and add value to the current value for a column in the table.
I used array to select and get values from the DB/tables for many times so i think the $arrWhere is not the problem.

well, found the answer,
for ex.:
This is working for me:
$id = 5;
$field = 'stock';
$amount = 1;
$increment = array($field => new FluentLiteral($field.' + '.$amount));
$fpdo->update('products')->set($increment)->where('id', $id)->execute();

Related

SQL query not working but works in PHPMyAdmin

I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);

How to select one value and match with other value from my database

I use codeigniter and store my data like 123,234 .
My table name is schedule and column name batch.
$batch = 123;
$lot =1;
$dataTest = $this->db->query("select q_set from schedule where lot='$lot'
and batch='$batch'")->row();
see my image below
I try to select one value and match my sent value. ## how to match both the values ##
the value of column batch in database is '123,321', and the variable $batch is 123,they are not equal so you can't select it.
you must send a data equal to the one in your database.
try
$lot=1;
$batch = 123321; //or $batch='123,321' i'm not sure the date type of variable $batch
$dataTest = $this->db->query("select q_set from schedule where lot='$lot' and batch='$batch'")->row();
Try this
$batch = "123,321";
$lot =1;
$dataTest = $this->db->query("select q_set from schedule where lot=".$lot."
and batch='".$batch."')->row();
or use
$batch = "123";
$lot =1;
$dataTest = $this->db->query("select q_set from schedule where lot=".$lot."
and batch like '%".$batch."')->row();
Using query builder. Please note if batch is a string it should be $batch = "123,234" plus you can't have commas with integers.
$this->db->select('q_set');
$this->db->where('lot', $lot);
$this->db->where('batch', $batch);
$q = $this->db->get('schedule');
if ($q->num_rows() > 0}
print_r($q->row());
} else {
echo 'no rows';
}
you can also use find_in_set.but it mostly used to find comma seperated values.
$this->db->select('q_set');
$this->db->from("schedule");
$this->db->where("FIND_IN_SET('$lot', lot)");
$this->db->where("FIND_IN_SET('$batch', batch)");
--------------OR---------------
you can try this..
$this->db->select('q_set');
$this->db->from('schedule as S1');
$this->db->where('S1.lot',$lot);
$this->db->where('S1.batch',$batch);
$query = $this->db->get();
return $query->row();
You can use IN Operator,
$result = $this->db->select('*')->from($table);
$result = $this->db->where('lot =',$lot);
$result = $this->db->where_in('batch',$batch);
$result = $this->db->order_by('id','desc');
$result = $this->db->get();
The where_in() operator checks if the value exists in the specified column

Mysqli query doesn't work with id from another table

I have this php script.
$cwZ = count($wiegen_zutat);
$cwM = count($wiegen_menge);
$cwS = count($wiegen_schritt);
if($cwM == $cwS and $cwM == $cwZ and $cwZ == $cwS){
for($x = 0; $x < $cwZ; $x++){
$aktZuat = $wiegenZutat[$x];
$qr = "SELECT ID_Zutat FROM Zutaten WHERE Name='$aktZutat' LIMIT 1";
$id_get = mysqli_query($verbindung,$qr );
$id = mysqli_fetch_array($id_get);
$zuatenID = $id['ID_Zutat'];
echo $id['ID_Zutat'];
echo $zutatenID;
$sql3 = "INSERT INTO Wiegen (ID_Zutat, Menge) VALUES ('$zutatenID', '$wiegenMenge[$x]')";
$wiegenEintragen = mysqli_query($verbindung, $sql3);
}
}
$wiegen_zutat, _menge, _schritt are all three arrays which contain the information from my form.
I go through the first array, and check the variable against a table which contains the ingredients for my website. I want to get the id of a ingredient which was added some steps before and add it into another table.
The problem is that neither the echos or the query are working.
What am I missing?
Please don't get confused by the name of the variables, I'm german :)
Best regards

PHP MYSQL filling an array with variables and change the field names

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

PHP POST via AJAX loop through javascript sent object literal

Hey all i normally grab the ajax sent js object literal by doing this:
$_POST['called']
$_POST['chk1']
etc etc...
But now i have a problem that i cant seem to find a solution for.
Depending on how many checkboxes are selected, i loop (using js) to see all checked boxes and add them to the js object that ends up looking like this:
doBulk = {
called: "Approved",
chk0: "1789156857",
chk2: "5134465673753",
chk3: "234123554646",
chk10: "25511545542"
};
Now the chkXX can be any number from 0-19 (so 20 check boxes per page). I am sending that just fine to my PHP page but i am unsure on how to go about looping to get the needed data to update the database.
$chk1 = $_POST['chk0'];
$chk2 = $_POST['chk1'];
$chk3 = $_POST['chk2'];
$chk4 = $_POST['chk3'];
$chk5 = $_POST['chk4'];
$chk6 = $_POST['chk5'];
$chk7 = $_POST['chk6'];
$chk8 = $_POST['chk7'];
$chk9 = $_POST['chk8'];
$chk10 = $_POST['chk9'];
$chk11 = $_POST['chk10'];
$chk12 = $_POST['chk11'];
$chk13 = $_POST['chk12'];
$chk14 = $_POST['chk13'];
$chk15 = $_POST['chk14'];
$chk16 = $_POST['chk15'];
$chk17 = $_POST['chk16'];
$chk18 = $_POST['chk17'];
$chk19 = $_POST['chk18'];
$chk20 = $_POST['chk19'];
I could do a lot of if than else to check to see if each has data but there has got to be a better way of doing that?
So if i am doing a bulk mySQL update then i would have to run a query for each checkbox that i have a value for above? Is there also a better way of updating all the records that are needed in one swoop?
$result = mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID = " . $chk1 . "");
Thanks!
UPDATE
foreach($_POST as $key => $value)
{
// $key = CHK1-20
// $value = XXXXXXXXX
$dbBuilder = $value . ", " . $dbBuilder;
}
$dbBuilder = '(' . $dbBuilder . ')';
$result = mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID in $dbBuilder");
You can pass in the id's inside an IN SQL Clause. So, for instance you will have:
UPDATE userAccount SET Accept = 1 WHERE ID in $idCollection
Where $idCollection will be all of the IDs checked, separated by commas and inside parentheses, like so:
(1, 2, 3)
For the looping, you can iterate through the $_POST array as you would in any other array, and populate this string with the values read.
Hope that helps
for ($i=1;$i<=20;$i++){
${'chk'."$i"}=$_POST["chk"."$i"];
}
For UPDATE, i think you can use Mysql create procedure like this
$query=mysql_query("CREATE PROCEDURE dorepeat(p1 INT) SET $i = 0; REPEAT SET #i = #i + 1; UPDATE userAccount SET Accept = 1 WHERE ID = ${'chk'."$i"}; UNTIL #i =p1 END REPEAT; END") or (die mysql_error());
$result=mysql_query("CALL dorepeat(20)") or (die mysql_error());
EDIT: perhaps this is better without using CREATE PROCEDURE.
for ($i=1;$i<=20;$i++){
${'chk'."$i"}=$_POST["chk"."$i"];
$exp.=${'chk'."$i"}.',';
}
$exp=substr($exp,0,-1);
$exp='('.$exp.')';
$query=mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID IN '$exp') or (die mysql_error());

Categories