Error in Comparing the same column in mysql - php

I am fetching the values from the column as the value of integer and doing this for two user so i tried to get the value from the table and compare it but unfortunately for both greater and smaller comparsion i am getting the same result nothing changed.
How do i compare the column values?
My code is like below-----
$sqlres="select membership from register where mid='".$_SESSION['mid']."' ";
$pres=mysql_query($sqlres);
$prest=mysql_fetch_array($pres);
$sqlres1="select membership from register where matri_id='".$row['mtr_id']."' ";
$pres1=mysql_query($sqlres);
$prest1=mysql_fetch_array($pres);
if($pres<$pres1)
{
//somethiung enter code here
}

First of all don't use mysql_* it is deprecated, use mysqli_* or PDO instead.
As for your question, mysql_fetch_array as the name suggests, returns an array, not a single value, so you need to get the first value in the array:
if($pres[0]<$pres1[0])
{
//somethiung enter code here
}

You save the result in $prest and $prest1 (with "t"), not in $pres and $pres1. I suggest always using the variable $query for the query string and $result for the result table. Only when you fetch the result should you use a custom variable name to not get confused.
You can use something like
if($prest['membership']<$prest1['membership']){//do stuff here}

In the piece of code that you provided, you are comparing the resources that mysql_query returned not the values of the columns. You have to do this:
if( $prest['membership'] < $prest1['membership'] ){
//Some stuff going here
}
Advice: Name your variables properly. Use more describing names. After 2 months you won't remember the difference between $prest and $prest1

Related

Drupal / MySQL fetchAllAssoc(); resulting in exception

I have an external database that I am trying to access from within a Drupal page, I have successfully queried the database and output data to the page using fetchAssoc(), however this only returns the first row in the database. I would like to return all rows into an array for processing, so I'm attempting to use fetchAllAssoc(), this however results in an exception. The database has the following SQL fields:
id, model, manufacturer, url, date_modified
My test code is as follows:
<?php
db_set_active('product_db');
$query = db_select('product', 'p')->fields('p');
$sqlresults = $query->execute()->fetchAllAssoc('id');
foreach($sqlresults as $sqlresult)
{
printf($sqlresult);
}
db_set_active();
?>
I'm thinking that it is the key field 'id' that I am specifying with fetchAllAssoc() that is the problem, as fetchAssoc() prints values correctly. All documentation I have found seems to say that you pass a database field as the key but I have also passed a numeric value with no success.
Many thanks in advance for any advice, I'm sure I'm just missing something stupid.
I think it should work in this way, but within the foreach you want to print the $sqlresult variable as a string, but it is an object (it causes the error).
printf function needs a string as the first parameter, see:
http://php.net/manual/en/function.printf.php
Use for instance var_dump instead:
var_dump($sqlresult);

PHP PDO - Understanding for beginners

I've read through PHP PDO Book and now have some basic questions:
If i understood correctly, i'll have to use begin_transaction() in order to turn off autocommit. If i am okay with autocommit, i am always good to go with a simple query()Is this correct?
Did i get it right, that there is basically no difference between query() and exec(), except of the above asked topic?
I made a query like this one:
foreach ($db->query('SELECT * from user') as $row) {
$row = json_encode($row);
echo $row;
}
Which returns a JSON Object:
{
"alias":"tk",
"0":"tk",
"password":"pw",
"1":"pw",
}
This is basically correct, however, why is each value returned twice, once with my chosen keyword and another time with an Integer key?
why is each value returned twice, once with my chosen keyword and another time with an Integer key?
The array has the values both with the column names as keys, and the column ordinals too. So you could access the values from the result set by using the number of which column you want. (of course, that does not seem to be of too much use with a select * statement...)
You can affect this behaviour with PDOStatement::setFetchMode(). The constants starting with PDO::FETCH_ are applicable here. Their documentation can be found here

Get row numbers from mysql_fetch_array result

I have pulled in the data from a mysql database using select * with the intention of using the data several times without doing repeated sql enquiries using WHERE.
Using this data I am extracting rows that contain a search element using
while($row=mysql_fetch_array($query_result)){ <<<if match add to new array>>> }
As there are thousands of rows this is taking a longer time than I want.
I am trying to use:
$row=mysql_fetch_array($query_result);
$a = array_search($word_to_check, $row);
echo $a;
This extracts the correct sql headings but not the row number. What I want to achieve is
if $word is found in mysql_fetch_array($query_result) the add the row where it was found into the new array for processing.
Any thoughts? Thanks in advance.
Don't use mysql_* functions they are depracated. Use mysqli or pdo instead.
It's not wise to search in array of mysql results in php while it can be done in mysql. Let's say you have table and you want to find all numbers in number column that are greater than 5
SELECT FROM table_name WHERE number>5
to find text you can use simple clause
SELECT FROM table_name WHERE name = 'username'
You can also create more complex conditions.
From MYSQL manual:
WHERE clause, if given, indicates the condition or conditions that rows must satisfy to be selected. where_condition is an expression that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause
Check this link
If you want to limit the query to only once, fetch all the results into temporary array and do the search from it like below
<?php
$all_rows=array();
$match_rows=array();
$i=0;
$limit=100000;
while($row=mysql_fetch_array($query_result)){
$all_rows[]=$row;
if($i % $limit == 0){ // this part only functions every 100,000 cycles.
foreach($all_rows as $search_row){
if(array_search($word_to_check, $search_row)
$match_rows[]=$search_row;
}
$all_rows=array();//reset temporary array
}
$i++;
}
//This solution assumes the required word can be found in mulitple columns

mysql In clause to avoid loop

I have to retrieve the history of a user and I have 4 tables whose data depend on each other.I can retrieve the data using loops,but I instead used the "where IN ()" clause and I implode the output of the previous query.However,if the list I provide to "where IN()" is empty it return an error.Is it that IN() cannot be empty?
When imploding an array for the IN clause, i do one of two things
1: Check if you even need to run the query at all
if(!empty($some_array)) {
//run mysql query
}
else {
// if you need to do something if the array is empty, such as error or set some defaults, do it here
}
2: A value in the array initiliser which is not ever in the database (for example, if im selecting based on a auto incrememnt id, i use zero as a default array value to stop any issues with empty data sets, as zero will never be in my id column).
$some_array = array(0);
You can add an empty value to the start, such as IN (0,your values here)

PHP: MySQL Query with fieldname in a var

Little question: With the following code...
<?php
$statement = "SELECT * FROM TABLE";
$query_unfetched = mysql_query($statement);
$query_num = mysql_num_rows($query_unfetched);
if ($query_num !== 1) {
exit;
}
$query_fetched = mysql_fetch_object($query_unfetched);
$fielname = "ID";
echo $query_fetched->$fiedname;
?>
With this code, there is no output, because PHP somehow does not check that in $fieldname is an existing name of a field in the selected Table.
Why doesn't it work, have I made a mistake? Or are there any other ways to select a field whose name is saved in a var?
Thanks for the help!
Instead of using mysql_fetch_object, you could use mysql_fetch_assoc. It will return the result as an array, after which you can simply use your variable as a key.
I'd suggest using var_dump on the $query_fetched. Some OS's and DB's will return different capitalizations. Oracle, for one, will always return the column names as capital. I've seen MySQL only return lower in one circumstance.
You can also use the fetch_assoc as suggested by Cpt. eMco and that will give you warnings if the array key is not set. (Remember to turn warnings off in production though).
(I do need to put in an obligatory plug for the PDO classes. I find them far more intuitive and clearer.)

Categories