Perform sql operations for this special case - php

Sir,
I am facing a problem and it is shown below:
I want to perform where opertion on the output of $this->db->select('*')->from('table'); only when cond1 satisfies
$result = $this->db->select('*')->from('table');
if(cond1)
{
I want to perform $result->where(); operation
}
Is it possible and i so what is the exact syntax to do it

try something like this:
$this->db->select('*');
$this->db->from('table');
if ($cond1)
$this->db->where(...)
$query = $this->db->get();

$con1 is should be a variable and it should has a value or Null. $con1 like a Boolean.1 or 0 .if 1(true) happening it'll execute the if block if not it'll execute the else block.

Looks like you want to run two different queries. Assuming that $cond1 is not dependent upon $result (in which case all bets are off), you can do something like
if(cond1)
$result = $this->db->select('*')->from('table')->where(...);
else
$result = $this->db->select('*')->from('table');

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.

Having trouble checking if MySQL query returned anything

Here's what I'm doing.
I'm checking if there's a "version" value in the URL with $get_version.
Get the latest version from the database and set as a default variable.
If the URL variable is good, check the database to see if it exists then set the appropriate variables.
If doesn't exist, use default value from above.
It always goes to the "Bad query section". Either my query is wrong or my if statement doesn't work.
Here's my code. Also, is there a cleaner way of doing it?
// Check if there's a version in URL. If not, set to empty.
$get_version = isset($_GET['version']) ? $_GET['version'] : '';
// Set defaults if nothing in URL
$query = "SELECT * FROM sn_hockey_versions ORDER BY version_id DESC LIMIT 1";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
$newest_version_id = $row['version_id'];
$newest_sections = $row['sections'];
}
if (!empty($get_version) && preg_match('/^[0-9.]*$/', $get_version)) {
$query = "SELECT version_id, sections FROM sn_hockey_versions WHERE version = '".$get_version."'";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
if ($row = mysqli_fetch_array($result)) {
$set_version = $row['version_id'];
$v_sections = $row['sections'];
$test = "IT WORKS!!!!";
}
else {
$set_version = $newest_version_id;
$v_sections = $newest_sections;
$test = "Bad query";
}
}
else {
$set_version = $newest_version_id;
$v_sections = $newest_sections;
$test = "Set default";
}
Your conditional if statement is checking to see whether $rows is set to mysql_fetch_array($result), not whether it returned any results. If the query returns results, the conditional statement returns true, $row is set to the resulting array, and your if block will be evaluated. Otherwise, $row is set to null, making the condition false, and the else block evaluates.
Since your else statement is evaluating, this leads me to believe that there is an issue with the query, which can be tested by printing out the results of the array. While there are numerous ways to check if a query returns any results, to prevent confusion in your code, checking the value of mysql_num_rows would be a better solution before fetching the results:
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result)
For more information about mysqli_num_rows check out http://php.net/manual/en/mysqli-result.num-rows.php
Also see: Whats the proper way to check if mysql_query() returned any results?
The other recommendation I have for making the code more efficient is: Only query the database for the default version when necessary. Too many unnecessary queries can lead to database performance issues. One way to accomplish this, is to place the default version query into a function and call it only in the "bad query" "set default" blocks. I hope this helps.
To check if it was successful outside of the code, copy the query and run it in phpmyadmin or through ssh to see if it returns results. If it returns results then put in some stop checks in your code to see what you are getting. like so
echo '<pre>jwow',print_r($result,1),'</pre>';
die('here');
Just place that under which ever result you would like to check. I like to name the query results by different names. like $defaults_results and $version_results . if it is getting to "Bad Query" you will have found your error after trying that. If it returns no results in phpmyadmin then read the errors it gives.

CodeIgniter Select Statement with Where clause

Hi I'm new to CodeIgniter and I just want to know How will I query from my MySql Db, a Select Statement with a where clause, I know it can be searched from the net but whenever I try something I get errors, It's really frustrating. The string in the Where clause will be coming from a User Input. Thanks guys!
You can do as Mehedi-PSTU stated, however it seems as though you're a little new to this, so here's some extra information:
I'll copy Mehedi-PSTU for the most part here.
$this->get->where('column_name', $equals_this_variable);
$query = $this->db->get('table_name');
This will store the query object in the variable $query.
if you wanted to convert that to a usable array, you just perform to following.
$results = $query->result_array();
Or you can loop through it like this:
foreach($query->result_array() as $result){
// Perform some task here.
}
A better or even full understanding can probably come from:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
Try something like this
$this->db->where('db_attr', $var);
return $this->db->get('table');
Try this one.
$id = 'your id';
$this->db->select("*");
$this->db->from("table_name");
$this->db->where('id','$id');
$query = $this->db->get();
return $query->result_array();
In Codeigniter with Method Chaining Style :-
$data['getData'] = $this->db->get_where('table_name',array('column_name'=>$var))->result_array();

PHP mysql error_log and immediately return a value

I'm writing a function that queries my database, and if the mysql query errors out for some reason, I'd like my function to return a value (in this case -1) indicating query failure, rather than dying out of the whole script.
Usually I just use this construct:
$result = mysql_query($sql) or die( [some error information] );
But in this case I don't want to die, but I do need to break out of the function and have some way to tell the calling function that something went wrong, while still being able to manually check the logs for the source of the error. Is there a way to do this? The semi-pseudocode would look something like:
$result = mysql_query($sql) or {
error_log( [some error information] );
return -1;
}
But I've tried a couple variations on that and (as one might expect) they don't work.
Any suggestions? Thanks.
Try this:
if(!($result = mysql_query($sql))) {
error_log(...);
return -1;
}
The or in that statement is one of PHP's logical operators which when used like that, will execute the second statement if the first one fails due to short circuit evaluation. You won't be able to return in that statement because you are doing assignment, and if you execute two statements, you won't be able to return a proper value to the $result variable.
You could do something like
$result = false or (error_log('message') && ($result = -1));
if ($result === -1) return $result;
but that isn't much shorter than anything else you can do.
Use an expression like what #Kolink provided to do what you want.

PHP get result string from PostgreSQL Query

I'm new to PHP and SQL, but I need a way to store the result of an SQL Query into a variable.
The query is like this:
$q = "SELECT type FROM users WHERE username='foo user'";
$result = pg_query($q);
The query will only return one string; the user's account type, and I just need to store that in a variable so I can check to see if the user has permission to view a page.
I know I could probably just do this query:
"SELECT * FROM users WHERE username='foo user' and type='admin'";
if(pg_num_rows($result) == 1) {
//...
}
But it seems like a bad practice to me.
Either way, it would be good to know how to store it as a variable for future reference.
You can pass the result to pg_fetch_assoc() and then store the value, or did you want to get the value without the extra step?
$result = pg_query($q);
$row = pg_fetch_assoc($result);
$account_type = $row['type'];
Is that what you are looking for?
Use pg_fetch_result:
$result = pg_query($q);
$account_type = pg_fetch_result($result, 0, 0);
But on the other hand it's always good idea to check if you got any results so I'll keep the pg_num_rows check.

Categories