if statement doesn't work in associtive array - php

I have the following problem. I am trying to write function that imports data from csv file. In this file in price column if there are sign like '<>' it means that price is in U.S. dollars and it needs to be converted. I understand that this variable is presented as a digit. How it could be converted to string? Or why the statement doesn't work at all? As always here is the source code.
$str='<>';
if( $variant['price'] ==$variant['price'].$str)
{
$sql = mysql_query("SELECT rate_to FROM s_currencies WHERE id=1 LIMIT 0, 30 ");
$course= mysql_fetch_row($sql);
//$rate=$course[0];
$variant_price = $item['price']*$course[0];
$variant['price']=$variant_price;
}
Please help!

The code which you have posted will not enter into if condition. Make a check with code.
For eg. if $variant['price'] = '1';
if ('1' == '1<>')
{
}
The above condition will not enter into if statement.

You need to check if that string exists, instead of using your current IF statement. strpos will give you want you need
if(strpos($variant['price'],$str) !== false) // <> is present
{
// run your sql code
}
I'd also suggest getting away from the mysql_* functions as they're deprecated. Look into PDO or mysqli queries, with bound parameters.

$str='<>';
if( stristr($variant['price'],$str){
$sql ="SELECT rate_to FROM s_currencies WHERE id=1 LIMIT 0, 30 ";
$qry = mysql_query($sql);
if ($qry && mysql_num_rows($qry)>0){
$variant['price'] = (str_replace($str,'',$variant['price'])*mysql_result($qry,0,0));
} else {
echo 'error while converting:' . mysql_error();
}
}

Related

PHP variable is not working with WHERE clause

My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.

Q: MySQL + PHP , Update values in multiple rows triggered by a "uniquevalue"

Database
I have these rows of "api_credit" and "api_select" .
The Value of "api_credit" decrements by '1' when it is triggered by a PHP file with the value called "Selected" in "api_select". IMAGE is attached with my question to get a better idea of DATABASE.
Now , the problem is that when it decrements, it decrements all values in "api_credit" which are "Selected".If one column value decrements to '18' , all other columns value becomes '18' if they are having that "Selected" term.
What i want is all of the values of "api_credit" to be "Selected" and want Database to First decrement value in first column of "api_credit" , when it reaches zero , then it should move-on to the next column of "api_credit" and start decrementing its value and so on .
Can Anyone please please please give me an idea of a PHP code to trigger this database behaviour as i want.
Iam new to MySQL and PHP , This database is keeping me frustrated , So Please Please i request you to help me write code in PHP for this database.
Give me any simple or complicated solution for this , iam sure i'll keep up with you.
CODE :
$sql = "SELECT * FROM site_api WHERE api_select = 'Selected'";
$querya = mysql_query($sql, $con);
if(!$querya)
{echo'no api selected'.mysql_error(); exit;}
$row = mysql_fetch_object($querya);
$api = $row->api_key;
$key = $row->secret_key;
include("network.php");
if (preg_match("/OK/", $result))
{
echo "Data has Not been Sent";
}
else
{
echo "Data has Been Sent.";
}
$cr = $row->api_credit;
$aid = $row->api_id;
$cr = $cr - 1;
if($cr <= 0){
$sql="UPDATE site_api SET api_credit='$cr', api_select='Expired' WHERE api_select='Selected'";
First of all, mysql_* functions are deprecated. Use mysqli_* instead!
Second of all, your code is open to SQL injections, use parameterized statements instead! More info on that in here: How can I prevent SQL injection in PHP?.
Finally, and regarding to your issue, if I get it correctly all you want to do is to decrease the value of the first row which has an api_select value of Selected. There are many ways to do this, but I'll just find what I need using LIMIT 1 first and then use the api_id value of that result (if there is any) to query the UPDATE. Here's what I'd do (not using parameterized statements):
$sql = "SELECT * FROM site_api WHERE api_select = 'Selected' AND api_credit > 0 LIMIT 1";
// I'll get only 1 row or none, and also making sure the api_credit is greater than zero.
$querya = mysqli_query($con, $sql);
if(!$querya){
echo 'No API selected. '.mysqli_error();
exit;
} else if(mysqli_num_rows($querya) == 1){
$row = mysqli_fetch_object($querya);
$api = $row->api_key;
$key = $row->secret_key;
/*include("network.php");
if(preg_match("/OK/", $result)){
echo 'Data has not been sent';
} else {
echo 'Data has been sent.';
}*/
// I'm commenting that out because I don't know where $result is coming from, maybe the included file?
$cr = $row->api_credit;
$aid = $row->api_id;
$sql = "UPDATE site_api SET api_credit = (api_credit - 1) WHERE api_id = '$aid'";
// I'm just decreasing within the SQL, but you can still do this with $cr--; outside, it's ok.
if(mysqli_query($sql)){
echo 'Value has been decreased.';
} else {
echo 'Value has not changed.';
}
} else {
echo 'If you can read this, something\'s really wrong!';
}
You can tweak this so that whenever $cr is equal to 0 at UPDATE time it also changes api_select to Expired as you said in your question.

If Statement proper formula

I have looked on here about if statements. I have found a few things but I am having issues figuring out the proper statement formula.
I have 2 tables in the database with the following 2 fields
table 1
rct_app_id
table 2
uid
now if the uid field matches the rct_app_id field I want it to
echo "Green Light";
if they don't match
echo "No Go"
this is my formula
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql);
$rct_app_id = ['rct_app_id'];
if ($rct_app_id == 'uid') {
echo "Green Light";
} else {
echo "No Go";
}
?>
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
Try this. but keep in mind its hard for people to figure out whats going on by bits and pieces and it makes it harder to help you.
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql);
while(($row = mysqli_fetch_assoc($result))!=false){
$rct_app_id = $row['rct_app_id'];
if ($rct_app_id == $user_id) {
echo "Green Light";
} else {
echo "No Go";
}
}
}
?>
You need to fix two lines. $result has the results from the database, so that's the source for the rct_app_id data. Then, when you do the comparison, you need to compare the two variables.
$rct_app_id = $result['rct_app_id'];
if ($rct_app_id == $user_id) {
The way you have it, you're comparing an array to a string.
When you do this:
$rct_app_id = ['rct_app_id'];
You're actually setting the variable $rct_app_id equal to an array with one element, although the syntax is incorrect. Instead, you need to get one element of the array that is returned from the database. This assumes that you have a function called query() that is working properly and returning an array.
Instead, we need to set the variable equal to one element of the array like so:
$rct_app_id = $result['rct_app_id'];
Then, when you do a comparison like this:
if ($rct_app_id == 'uid') {
you're saying if the variable $rct_app_id is equal to the string uid, which it's not. Variables always start with $ in php, strings are quoted. The variable set earlier in the script is $user_id (from SESSION), so we need to compare to that:
if ($rct_app_id == $user_id)
UPDATE: You've specified your sql lib, I've edited the answer below to work with your updated answer.
Since you didn't specify the library, I'm making the answer and the code edits with the assumption that you're using mysql. Though all queries and return functions use similar syntax, ie: mysql_fetch_assoc() = mysqli_fetch_assoc(), pg_fetch_assoc(postgres).
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql); //What type of query runs as just query()? mysql_query would go here if this was mysql. Some Libraries offer this as a function, but since you didn't specify the library, I'm going to change it to mysql_query and proceed as if you're using mysql.
//$rct_app_id = ['rct_app_id'];//This will never work.
//You need this:
while($row=mysqli_fetch_assoc($result)){
//We only expect one result
$rct_app_id=$row['rct_app_id'];
}
if ($rct_app_id == 'uid') {
echo "Green Light";
} else {
echo "No Go";
}
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
?>

if preg_match does not change var to false

Ive been studying "the missing manual" by brett m. Its out of date. I.ve been replacing mysql func. Thats not the problem. I run an if statement to match a sql command using preg match. Before the if I set a var to true. If preg match returns a match, var is then changed to false. If does not run. Script executes to mysqli_fetch. Please help.
$return_rows=true;
If(preg_match("/^\s*(CREATE|INSERT|UPDATE|DELETE|DROP)/i", $query_text))
{
$return_rows=false;
}
If($return_rows)
{
While($row=mysqli_fetch_row($result)){ echo $row[0]; }
}
else{ echo "query processed"; }
mysqli_close($u);
Just cover the SELECT query. cause SELECT is the main query of requesting data from database.
if( strtolower( substr( trim( $query_str ) ) , 0, 6) == "select"){
// SELECT query is being requested
while($row=mysqli_fetch_row($result)){ echo $row[0]; }
else{ echo "query processed"; }
mysqli_close($u);
Now, you can continue your works without any problems
Instead of using an if to only update your $return_rows in one of the cases, assign the regex match result directly:
$return_rows = !preg_match("/^\s*(CREATE|INSERT|UPDATE|DELETE|DROP)/i", $query_text);
The ! here is a negation. You might want to use a more appropriate variable name instead.
Then use your if check to fetch rows, or print a message else:
if ($return_rows) {
// fetch rows
}
else {
// no fetching
}
Also consider using PDO instead of mysqli. It's way less circuitous with parameter binding.

PHP mysql result issue

I have this line in my registration page.
if (device_id_exists($_POST['device_id']) == true) {
$errors[] = 'Sorry the Serial Number \'' . htmlentities($_POST['device_id']) . '\' does not exist.';
}
I have this in my function page.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$numbers'");
return (mysql_result($query, 0) == 0) ? true : false;
If I run this query SELECT COUNT(numbers) FROMdevicenumbersWHEREnumbers= '1234567890'
(a valid number) it will return 1 = match found right? If I put a bogus number it returns a '0'.
What is happening is when there is a valid number it still returns the error the number doesn't exist. If I change it to the result to == 1 it will submit any number? Im a newbie to DB calls any help appreciated. I hope I provided enough info.
Looks like you're calling the incorrect variable. Within the device_id_exists() function, you're accepting a variable named $device_id. However when you're performing the query, you're calling what appears to be an undefined variable: $numbers. I suspect $numbers should be renamed to $device_id.
I see your $device_id comes from a form post. I'd HIGHLY recommend you escape the variable, using mysql_real_escape_string() to ensure you are protected against SQL injection. Please note that sanitize() does NOT protect against SQL injection!
On one additional note, I'd recommend utilizng mysql_num_rows() rather than mysql_result() because mysql_result() actually asks the database server to return an actual result when all you really care about is whether the entry exists or not, not it's actual value.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$device_id = mysql_real_escape_string($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$device_id'");
return mysql_num_rows($query) ? True : False;
}
I had a similar problem with mysql result set , It returns nums_rows == 1 even when there are no records (while using max() inside select query - In your case you have used count())... Instead of checking mysqlquery to 0, check it whether the result set empty (That's how i solved my problem).. eg. if(!empty(mysql_result($query))) ? true : false;

Categories