Check if value exists In MySQL row - php

I have a php variable: $foo
My MySQL table called data has the following structure:
id var header
1 zj3 http://google.com
I would like to check if $foo is all ready in var row.
If it is I would like to echo header ("http://google.com")
How would you approach this?
Thanks in advance, please ask if any clarification is needed!

Your query should be:
SELECT `header` FROM `data` WHERE `var` = '$foo'
This will return all the headers with a var value of $foo.
$db = mysqli_connect('localhost', 'username', 'password', 'database');
if($query = mysqli_query($db, "SELECT `header` FROM `data` WHERE `var` = '$foo'")){
while($row = mysqli_fetch_assoc($query)){
echo $row['header'];
}
mysqli_free_result($query);
}

first connect to the db
$query = mysql_query("SELECT var, header FROM data WHERE id='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)){
if($foo == $row['var']){
echo $row['header'];
}
}
EDIT: changed equality statement based on your edit

It's not difficult at all, If I understand correctly then this should help you.
// Query Variable / Contains you database query information
$results = $query;
// Loop through like so if the results are returned as an array
foreach($results as $result)
{
if(!$result['var'])
echo $result['header'];
}
// Loop through like so if the results are returned as an object
foreach($results as $result)
{
if(!$result->var)
echo $result->header;
}

are you asking if $foo matches any of the fields in data, or if $foo=some_field? Here for if you want $foo==var.
$foo='somevalue';
$query="SELECT id, var, header FROM `data` WHERE var='$foo'";
$result=mysqli_query($query);
if($result->num_rows==0)
$loc= 'http://google.com';//default value for when there is no row that matches $foo
}else{
$row=$result->fetch_assoc(); //more than one row is useless since the first header('Location: x') command sends the browser to a new page and away from your script.
$loc=$row['header'];
}
header ("Location: $loc);
exit;
ETA: since you've edited your question, it appears that you want to echo the header column if your search value matches your var column. The above won't work for that.

You just want to know if $var's value is anywhere in that column (any row(s))?
SELECT COUNT(id) FROM data WHERE var = ?;
The result will be the number of rows for which the field var contains the value of $var.

Here's a template for all the "does it exist" questions.
This is the only thing that actually worked for me so far and is not deprecated.
if ($query = mysqli_query($link, "SELECT header FROM data WHERE var = '$foo'")) {
$header = mysqli_fetch_assoc($query);
if ($header) {
// The variable with value $foo exists.
}
else {
// The variable with value $foo doesn't exist.
}
}
else {
// The query didn't execute for some reason. (Dammit Obama!)
}
WARNING!
Even if the variable DOES NOT EXIST the comparison between $query and mysqli_query() will always return TRUE.
The only way --which happened to me-- for the comparison to return FALSE is because of a syntax error in your query.
I don't know why it worked for the guy who wrote the accepted answer, maybe it's an update or maybe he had a syntax error and was so confident that he didn't check if it could ever be TRUE.
Here's the comment someone made for correcting his syntax:
"Add another ) before the { in the first line"
So, the accepted answer is WRONG!

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.

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);
}
?>

Getting information from MySQL

I'm having trouble getting info from my MySQL database.
Here is my code :
/********************
* Database Info
********************/
$host = "localhost";
$user = "admin";
$pass = "admin#";
$database = "db_admin";
/********************
* Database connection
********************/
$con = mysqli_connect( $host, $user, $pass, $database );
if (mysqli_connect_errno ()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}
$result = array();
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
$query = "SELECT * FROM Servers WHERE PID='" .$id. "'";
$result = mysqli_query($con, $query);
}
print("<pre>".print_r($result,true)."</pre>");
My first question, Did I use "isset" function currectly?
Because it doesnt seem like it is actually going though the if statement.
The Url I am using is : #..com/view.php?ID=1
My second question, Did I use the $query correctly?
Because I echo $id and that echoed out a "MySQL Object()"
Finally, the print printed out "Array()"
I'm just starting on PHP, Thanks for the help :)
A few things:
If you're passing the variable in the query string, use $_GET instead of $_POST to retrieve the values.
$result will return an pointer to the recordset, not the rows themselves. You will have to use mysqli_fetch_array() to fetch the rows.
ADD:
If you are sure that you will only have 1 record returning, you can use:
$row = mysqli_fetch_assoc($query);
echo $row['field_name'];
More then 1 record?
while($row = mysqli_fetch_assoc($query)){
echo $row['field_name'];
}
# your first question: if you have a input field with the name="ID", then its good.
Please also post your HTML :)
$var = 'Hello world';
if(isset($var)){ //If the var $var has been set (in this case it is)
echo $var;
} else {
//If $var is not set, then we get in the else
echo 'The var $var is not set';
}
The best thing is debugging the code with a debugger, you may use XDebug, or at least use var_dump(); to see what happens
var_dump($_REQUEST, $result);
Answer to your first question: It's hard to say if you've used it correctly when you haven't said what you're trying to do. I'm presuming that you only want run the code enclosed in the if-statement if the POST variable 'ID' has been received. If so, yes you've done it correctly.
Answer to your second question: I'm presuming on this line you're trying to build a string with a valid MySQL query. You've done that correctly, assuming $_POST['ID'] is a string (or can be converted to a string, see http://www.php.net/manual/en/language.types.string.php#language.types.string.casting).
If you're echoing $id and it's returning an object, however, you'll have a problem. You can't combine a string and an object like that. You'd need to iterate the object with a foreach, for example, and extract the id from that. The rest of the code won't work until that part is resolved.
The thing to investigate now is why $_POST['ID'] is returning an object. You'll need to provide the form code at the very least.

Basic mysqli select

I have a select statement where I want to get all rows from a table but seem to be having a mental blockage - this should be elementary stuff but can't seem to get it working.
There are only two rows in the table 'postage_price' - and two columns : price | ref
Select statement is as follows:
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[]=$post_row;
}
I am then trying to echo the results out:
echo $post1['0'];
echo $post1['1'];
this is not showing anything. My headache doesn't help either.
while($post_row = mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[] = $post_row['price'];
}
As you see: $post_row in this line: = mysqli_fetch_array($dbc, $get_postage_result) is an array. You are trying to save the whole array value to another array in a block. :)
EDIT
while($post_row = mysqli_fetch_array($get_postage_result))
...
You have $post1[]=$post_row; and $post_row is itself an array. So you can access post data with following: $post1[NUMBER][0] where NUMBER is a $post1 array index and [0] is 0-index of $post_row returned by mysqli_fetch_array.
Probably you wanted to use $post1[]=$post_row[0]; in your code to avoid having array of arrays.
You are passing 1 and 0 as string indexes, this would only work if you had a column called 0 or 1 in you database. You need to pass them as numeric indexes.
Try:
print_r($post1[0]);
print_r($post1[1]);
or
print_r($post['price']);
print_r($post['ref']);
with all your help I have found the error - it is in the mysqli_fetch_array where I had the $dbc which is not required.
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($get_postage_result))
{
$post1[]=$post_row['price'];
}
instead of:
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[]=$post_row['price'];
}
Bad day for me :(
Thanks all
If something does not work in a PHP script, first thing you can do is to gain more knowledge. You have written that
echo $post1['0'];
echo $post1['1'];
Is showing nothing. That could only be the case if those values are NULL, FALSE or an empty string.
So next step would be to either look into $post1 first
var_dump($post1);
by dumping the variable.
The other step is that you enable error display and reporting to the highest level on top of your script so you get into the know where potential issues are:
ini_set('display_errors', 1); error_reporting(~0);
Also you could use PHP 5.4 (the first part works with the old current PHP 5.3 as well, the foreach does not but you could make query() return something that does) and simplify your script a little, like so:
class MyDB extends mysqli
{
private $throwOnError = true; # That is the die() style you do.
public function query($query, $resultmode = MYSQLI_STORE_RESULT) {
$result = parent::query($query, $resultmode);
if (!$result && $this->throwOnError) {
throw new RuntimeException(sprintf('Query "%s" failed: (#%d) %s', $query, $this->errno, $this->error));
}
return $result;
}
}
$connection = new MyDB('localhost', 'testuser', 'test', 'test');
$query = 'SELECT `option` FROM config';
$result = $connection->query($query);
foreach ($result as $row) {
var_dump($row);
}

PHP mySQL 404 function

The following function is designed to check whether this row in this tables exists. I know that it does not yet whether I $row or !$row the if function it does not do anything.
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
while($row = mysql_fetch_array($four_zero_four)) {
echo 'no'; die();
}
};
$name is the name field from the row and is working correctly in other functions.
Another way to check whether a row exists is by using the mysql_result function in conjunction with the COUNT function as such:
$query = mysql_query("SELECT COUNT(1) FROM `table` WHERE `field` = 'something'");
$result = mysql_result($query, 0);
When you now print out the $result variable, you will see the amount of rows that are actually being returned by the query. This is generally faster than using mysql_num_rows.
I'm not sure I understand the logic, aren't you printing "no"; die() when there IS a row found, instead of when now row is found? Either way, here's how I would check:
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
if (mysql_num_rows($four_zero_four) == 0) {
// ROW DOES NOT EXIST
} else {
// ROW EXISTS
}
};
Your code does not work because it wont even be executed if there is no row returned by your query.
Use mysql_num_rows() instead:
$count = mysql_num_rows($four_zero_four);
if($count <= 0){
die("no rows in this table!");
}
Also, you should maybe consider to use MYSQLi commands instead of the old mysql_query() implementation and SELECT *, as they are deprecated.

Categories