mysql divison by zero error - php

I am trying to use PHP to update column data but I am receiving a division by zero error.
mysql_query('UPDATE personas SET toolbar_id=\'' . $result . '\' WHERE download_ff LIKE concat('%',\'' . $result . '\','%')');
echo mysql_error($link);
printf("Records inserted: %d\n", mysql_affected_rows());
Ive tried a few ways to concat the $result but it is all resulting in a division by zero error. Help!

Your problem is right here:
concat('%',\'' . $result . '\','%')
The % ends out outside the string so PHP is interpreting it as a modulus operation and the strings on both sides of the modulus will be zeros in a numeric context, the result is that you're trying to 0 % 0 and you get your "division by zero" error.
Try escaping the inner single quotes:
concat(\'%\',\'' . $result . '\',\'%\')
Or, create a $like_result in your PHP that includes the percent signs in the string and then do this:
mysql_query('UPDATE personas SET toolbar_id=\'' . $result . '\' WHERE download_ff LIKE \'' . $like_result . '\';
You are using mysql_real_escape_string too, right?

How about using single quotes for PHP and double quotes for SQL, that way you don't have to mess around with backslashes to escape quotes; using some whitespace also helps to make query better to read:
mysql_query(
'UPDATE personas SET
toolbar_id="' . $result . '"
WHERE
download_ff LIKE "%' . $result . '%" ' );

Did not debug about the divistion by zero error.
But your problem seems to be improper string formatting and concatenation,
PHP might be treating % as modulus operation with empty string ( i.e. 0 );
<?php
$a = 10;
$b = a%'';
?> /* would give : Warning: Division by zero on line 4 */
Try the second version of the query, it would work :
http://codepad.org/6erRjYa7
<?php
$result = "foo";
$query = $query = 'UPDATE personas SET toolbar_id=\'' . $result . '\' WHERE download_ff LIKE concat('%',\'' . $result . '\','%')';
echo $query;
$queryNew = "UPDATE personas SET toolbar_id='".$result."' WHERE download_ff LIKE concat('%','".$result."','%')";
echo PHP_EOL ;
echo $queryNew;
?>

Related

Wrong calculations in PHP

I am trying to calculate in PHP. When I try to do that I can see that the result is mostly wrong.
The script I am using is the following:
$newrate = 1 / $rate["rate"];
echo '1 /'. $rate["rate"]. ' = '.$newrate;
The result I get is the following:
1 /1.0867 = 1
1 /117.01 = 0.0085470085470085
1 /1.9558 = 1
1 /27.534 = 0.037037037037037
1 /7.4589 = 0.14285714285714
1 /1.0867 should be 0.92021717125 and not 1.
I can reproduce this step by adding the following line to my script:
$rate["rate"] = 1.0867;
When I run the script the result is still 1. When I change my script like:
$newrate = 1 / 1.0867;
echo '1 / 1.0867 = '.$newrate;
I get a correct result. The output is then: 0.92021717125.
Does someone know what is wrong with this script? What is the reason that my script is making incorrect calculations?
Update 1:
Here is my full script:
<?php
$XML=simplexml_load_file("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml");
foreach($XML->Cube->Cube as $rat)
{
foreach($rat as $rate)
{
$newrate = '1' / $rate["rate"];
echo '1 /' . $rate["rate"] . ' = ' . $newrate;
echo '<br /><br />';
}
}
?>
I think there is something wrong with your example. I tested exactly what you described and works as expected.
<?php
$rate = [];
$rate["rate"] = "1.0867";
$newrate = 1 / $rate["rate"];
echo '1 / ' . $rate["rate"] . ' = ' . $newrate;
// 1 / 1.0867 = 0.92021717125242
You can see it running here
https://repl.it/#thiagodamata/NeighboringPeachpuffArchitect
Probably, you are using "," instead of "." when sending the number.
PHP cast the number only until it hits something unexpected. So "1,0867" is cast to 1. It is a classic problem when dealing with numbers in different formats, considering different languages.
<?php
// simulating the "," error
$rate["rate"] = "1,0867";
$newrate = 1 / $rate["rate"];
echo '1 / ' . $rate["rate"] . ' = ' . $newrate;
// 1 / 1,0867 = 1
Take a look in this thread about how to cast the number from different languages masks PHP: Locale aware number format and take a deeper look into the PHP function number-format https://www.php.net/manual/en/function.number_format.php
Update - After getting the full code example
Looking to your full code becomes more clear the problem. The var that you are getting in the loop it is a SimpleXmlElement, not a string. So, SimpleXmlElement is printed as the "1.0867" but it is not its real value.
To make the SimpleXmlElement cast to float properly, you need to use the cast function.
<?php
$XML=simplexml_load_file("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml");
foreach($XML->Cube->Cube as $rat)
{
foreach($rat as $rate)
{
print(var_dump($rate["rate"]));
/*
object(SimpleXMLElement)#7 (1) {
[0]=>
string(6) "1.0867"
}
*/
print("class = [" . get_class($rate["rate"]) . "]\n");
// class = [SimpleXMLElement]
print("as string = [" . $rate["rate"] . "]\n");
// as string = [1.0867]
print("without cast = [" . (1 * $rate["rate"]) . "]\n");
// without cast = [1]
$a = (float)($rate["rate"]);
print("with cast = [" . ($a) . "]\n");
// with cast = [1.0867]
print(serialize($a));
//d:1.0867;
$newrate = '1' / $a;
echo '1 / ' . $a . ' = ' . $newrate . "\n";
// 1 / 1.0867 = 0.92021717125242
echo '<br /><br />';
exit();
}
}
?>
You can see this running here:
https://repl.it/#thiagodamata/FuchsiaLightheartedPrintablecharacter
Just printing the value of a var does not always give you the real value of some object. There are other functions like var_export https://www.php.net/manual/en/function.var-export.php, var_dump https://www.php.net/manual/en/function.var-dump.php and serialize that may help you to see the real value of the vars.
Calculations are fine, and correct
You've not taken into account implicit type casting in PHP. Try this:
<?php
print "integer divided by float = " . (1 /1.0867) . "\n"; // returns 0.9202171712524
print "Integer divided by string = " . ((1/"1.0867") . "\n"; // returns 1
You are expecting PHP to know what your intention is when you throw a tring into an arithmetic operation - that's not how PHP works.
Just because it is dynamically typed doesn't mean you don't need to be careful with your data types.
print (1/(float)$rate['rate'];
try cast all values as a float
echo 1.0 / (float) $rate['rate'];

on click link display string which first character is between 0-9

Am trying to display a string from my database where the first character is between 0 to 9 i tried it but still did not work below is my code help me with it thanks.
if(isset($_REQUEST['num'])){ $num = explode('-',$_REQUEST['num']);
$query1 = "SELECT usercode FROM user WHERE code like '".$num."%'" ORDER BY id DESC ";
$result1 = mysql_query ($query1) or die('query error');
while( $line1 = mysql_fetch_assoc($result1)){
echo $line1[usercode];
}
#
Your code is currently searching your database for Array since you are explode()'ing the $_REQUEST['num'], which returns an array.
You may want to create a range of numbers from your $num and then do multiple LIKE's or maybe try with a REGEXP.
Use the REGEXP function in MySQL to match code to ^[0-9] which means: "the first letter must be between 0 and 9" and in ASCII, they happen to be the numbers between 0 and 9.
This will do what you want:
<?php
if (isset($_REQUEST['num'])) {
$num = explode('-', $_REQUEST['num']);
$query1 = "SELECT usercode FROM user WHERE code REGEXP '^[" . $num[0] . "-" . $num[1] . "]' ORDER BY id DESC";
$result1 = mysql_query ($query1) or die('query error');
while ($line1 = mysql_fetch_assoc($result1)) {
echo $line1['usercode'];
}
}
?>
#
cOle2 is also right about the explode function. It returns an array, the elements of which are the input string tokenized by some delimiter. In your case, $_REQUEST['num'] based on a delimiter -.

Update multiple rows/columns in php/mysql

I have the following line:
$reset = "UPDATE pidgeon SET obt='" . $hour . "' WHERE tag='" . $tag . "'";
Which updates just fine. However I need to update an additional row (kill) and I keep getting syntax errors. I've tried the following:
$reset = "UPDATE pidgeon SET obt='" . $hour . "', kill='1' WHERE tag='" . $tag . "'";
$reset = "UPDATE pidgeon SET kill='1', obt='" . $hour . "' WHERE tag='" . $tag . "'";
$reset = "UPDATE pidgeon SET obt='" . $hour . "', kill='" . $num . "' WHERE tag='" . $tag . "'";
I've even done 2 separate UPDATE queries and I get the same syntax error message. I've narrowed it down to the system having issue with the kill row but I'm not sure what's the issue. I've tried setting kill as INT, SMALLINT, BOOL, even CHAR and trying to use 't/f' as values for it. I still get a syntax error. Any suggestions?
KILL is a reserved keyword, so you'll have to enclose it in backticks, like so:
$reset = sprintf("UPDATE pidgeon SET `kill`='1', obt='%s'
WHERE tag='%s'", $hour, $tag);
Kill is actually a syntax, you can't use them directly.
Just replace kill with another name.

How to round mysql column in a table output

I need to round a result of a SQL round in a table array output. I can't figure out the syntax...
$result = mysql_query("SELECT `Energ_Kcal`*`yield`*`qty` AS `cal` FROM allinnot a
WHERE `own_id` = $user->id");
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . "</td><td>" . $row['cal'] . " cal</td></tr>";
cal returns a value with many numerals beyond the decimal. I just need it to show a whole rounded integer. I tried ROUND(), but I must be putting it in the wrong place.
general syntax
ROUND( expression, 2 )
The ROUND should go around the values, try this:
$result = mysql_query("SELECT ROUND(`Energ_Kcal`*`yield`*`qty`,2) AS `cal` FROM allinnot a
WHERE `own_id` = $user->id");
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . "</td><td>" . $row['cal'] . " cal</td></tr>";
You could also check out PHP's round() or, possibly from your description int_val().

Why does this line of PHP not pass the data correctly to the function?

My apologies I can not give the source for the $db class.
Why does this line of PHP in between the () give e an error?
$q = $db->sqlQuery("SELECT * FROM realsteal WHERE email = " . $db->decrypt($email) " OR cell = " . $db->decrypt($cell) ");
You're missing a concatenation operator after $email) and an errant "
However, please stop writing queries via string substitution and move to prepared statements ASAP.
You have some syntax errors. Here 's the correct line:
$q = $db->sqlQuery("SELECT * FROM realsteal WHERE email = " . $db->decrypt($email) . " OR cell = " . $db->decrypt($cell));
$q = $db->sqlQuery("SELECT * FROM realsteal WHERE email = " . $db->decrypt($email) " OR cell = " . $db->decrypt($cell) ");
misses a concatenator after $db->decrypt($email)
and there is an extra " before );
$q = $db->sqlQuery("SELECT * FROM realsteal WHERE email = " . $db->decrypt($email) . " OR cell = " . $db->decrypt($cell) );
You have an extra " in the end. And a missing concatenation operator.
"SELECT * FROM realsteal WHERE email = " . $db->decrypt($email) . " OR cell = " . $db->decrypt($cell)
Also, I don't know what your decrypt method does, but if $email and/or $cell are strings, you should mark them as a string in the SQL statement (put ' around them).
Honestly, you should look into using PDO and prepared statements. It would clean up this mess.
You are missing concatenation operator and have extra quote in the end of the query. The correct code would be:
$q = $db->sqlQuery("SELECT * FROM realsteal WHERE email = " . $db->decrypt($email) . " OR cell = " . $db->decrypt($cell));

Categories