How to += string with sql query using php? - php

Uncaught mysqli_sql_exception: Truncated incorrect DOUBLE value: '0-' in ... Stack trace: #0 ...(68): mysqli->query('UPDATE `Results...') #1 {main} thrown in ... on line 68
That's the error I am getting with the ellipses representing the file pathway.
The php I have:
for($i = 1; $i < $maxQuestions; $i++){
$answer = $_POST["question$i"] == "Yes" ? "1-" : "0-";
$connection->query("UPDATE `Results`
SET `question$i` = `question$i` + '$answer'
WHERE `ID` = '$id'");
}
The problem is with the SET `question$i` = `question$i` + '$answer' as I am trying to basically keep a history of the question's answers. For example, I may want the stored data to go from "0-" to "0-1-". How do you += a string with php/sql?
EDIT:
I have tried SET `question$i` = concat(`question$i` + '$answer') and I am getting the same error.

I changed it to
for($i = 1; $i < $maxQuestions; $i++){
$answer = $_POST["question$i"] == "yes" ? "1-" : "0-";
$qColumn = "question" . strval($i);
$questionData = $data["question$i"] . $answer;
$connection->query("UPDATE `Results`
SET `$qColumn` = '$questionData'
WHERE `ID` = '$id'");
}
This worked, but I'm still not sure why my initial code did not work. If someone could post a better answer/solution and why my initial code didn't work, please do. Thanks!

In mysql You can do it dierctly using concat this way
SET `question$i` =concat(`question$i`, '$answer')

You should not have column names ending with numbers because this is an indicator that your schema is not correct. You should normalise the database and have questions as a separate tables joined to your results table. Your results should not be concatenated into a single column either. Have a separate row for each result.
However, if you want to achieve this with your current set-up you could use CONCAT(). The query should look similar to this:
$types = '';
$setString = [];
$values = [];
for($i = 1; $i < $maxQuestions; $i++){
// concat types
$types .= 's';
// gather values
$values[] = isset($_POST["question$i"]) ? "1-" : "0-";
// build SET statement
$columnName = "question" . $i;
$setString[] = $columnName.' = CONCAT('.$columnName.', ?)';
}
$sql = "UPDATE Results SET ".implode(', ', $setString).' WHERE ID = ?';
$stmt = $connection->prepare($sql);
$stmt->bind_param($types, ...$values);
$stmt->execute();

Related

Prevent text from being interpreted as a number

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;

Code creates two MySQL rows instead of one

I´m trying to create just one new row in a MySQL table
The problem is that I´m getting two new rows in my database.
I really can´t see why this is happening. The debug_to_console( "makepass" ); - my debug function - only gets executed once? AND the two rows it creates is not identical/copies
debug_to_console( "makepass" );
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$len = strlen($salt);
$makepassJBH = '';
for ($i = 57; $i < $len; $i ++) {
$makepassJBH .= $salt[mt_rand(0, $len -1)];
}
$newpassJBH = password_hash($makepassJBH, PASSWORD_BCRYPT );
$licensidentifierJBH = '';
for ($i = 57; $i < $len; $i ++) {
$licensidentifierJBH .= $salt[mt_rand(0, $len -1)];
}
$fullkey = $makepassJBH . $licensidentifierJBH;
try {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Insert columns.
$columns = array('licenskey','licenskey_Identifier','dateCreated', 'printed');
// Insert values.
$values = array($db->quote($newpassJBH), $db->quote($licensidentifierJBH), $db->quote(date("Y-m-d")), $db->quote(0));
// Prepare the insert query.
$query
->insert($db->quoteName('#__licenskey'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$query .= ' ON DUPLICATE KEY UPDATE ' . $db->quoteName('licenskey_Identifier') . ' = VALUES(' . $db->quoteName('licenskey_Identifier') . ')';
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
echo $db->replacePrefix((string) $query);
$db->execute();
}
The SQL dump:
INSERT INTO `mdh_licenskey` (`licenskey`,`licenskey_Identifier`,`dateCreated`,`printed`) VALUES ('$2y$10$jXkjJX1OZ7Vu0okV/QlxcehF5T2SSPZFhVHIx.E64HhidgYY.3URS','juLEo','2018-07-23','0') ON DUPLICATE KEY UPDATE `licenskey_Identifier` = VALUES(`licenskey_Identifier`)
Since the license key is generated by the PHP code above, that code must be executed twice. This can happen for multiple reasons but it can be difficult for us to guess exactly why. Either check if your browser is calling it twice, or if it is called twice from within the PHP code.
Make sure your script isn't executed twice. I had this issue when using firebug for example. This plugin made my page execute twice but not outputting to the console.
Sort of like a "prefetch" of the page before showing, don't know for sure.
Maybe add a 'debug to console' point on every line, like 'here 1, here 2'..

transform sql query to Fluentpdo query

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();

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

How to get a loop query into one query in php

I got something like this.
It's working, but have to do a mysql query like 40 times is not the best thing.
Can somebody help me get it in to one query?
$string_unique = 'Unique string';
$number = count($something);
for ($i=0; $i < $number; $i++)
{
if(!empty($some_input)) {
$string_one = 'Something_one' . $i;
$string_two = 'Something_two' . $i;
mysql_query("INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES('$unique_string', '$string_one', '$string_two') ON DUPLICATE KEY UPDATE `string_one` = '$string_one', `string_two` = '$string_two'") or die(mysql_error());
} else {
$string_one = '';
$string_two = '';
mysql_query("INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES('$unique_string', '$string_one', '$string_two') ON DUPLICATE KEY UPDATE `string_one` = '$string_one', `string_two` = '$string_two'") or die(mysql_error());
}
You can generate a single query in that loop and then execute it only once:
$query = 'INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES ';
$queryValues = array();
$string_unique = 'Unique string';
$number = count($something);
for ($i=0; $i < $number; $i++)
{
if(!empty($some_input)) {
$string_one = 'Something_one' . $i;
$string_two = 'Something_two' . $i;
$queryValues[] = sprintf('("%s", "%s", "%s")', $unique_string, $string_one, $string_two);
} else {
// I can't understand what are you using this part for... Anyway.
$queryValues[] = sprintf('("%s", "", "")', $unique_string);
}
}
$query .= implode(', ', $queryValues);
// And here is the unique key updating.
// I don't know whole the structure, so I just guess you have the PRIMARY `id` row
// What you did in your ON DUPLICATE KEY was unnecessary.
$query .= ' ON DUPLICATE KEY UPDATE `id`=`id`';
// Don't use mysql_* functions in new code.
// See: http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php
mysql_query($query);
You're a allowed to add multiple rows of data in an insert statement in MySQL. That way, you can build one big insert statement in the loop, and execute it in one go after the loop. That is way faster and much more efficient.
You can insert multi row with sql,
here an example
insert into table1 (First,Last) values ("Fred","Smith"),
("John","Smith"),
("Michael","Smith"),
("Robert","Smith");

Categories