mySQL/PHP: SQL Statement, query and result assignment in ONE line? - php

Is it possible to re-write the code below, maybe even with an if (result > 0) statement, in just one line (or simply shorter)?
// a simple query that ALWAYS gets ONE table row as result
$query = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id = $result->id;
I've seen awesome, extremely reduced constructs like Ternary Operators (here and here - btw see the comments for even more reduced lines) putting 4-5 lines in one, so maybe there's something for single result SQL queries like the above.

You could shorten
$query = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id = $result->id;
to
$id = $this->db->query("SELECT id FROM mytable WHERE this = that")->fetch_object()->id;
but this, and the original code will emit errors, if any of the functions returns an unexpected response. Better to write:
$query = $this->db->query("SELECT id FROM mytable WHERE this = that");
if (!$query) {
error_log('query() failed');
return false;
}
$result = $query->fetch_object();
if (!$result) {
error_log('fetch_object() failed');
return false;
}
$id = $result->id;

Related

How to get SELECT EXISTS() query value

I have this php code:
$query = $database->query("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID')";
if($query == 0){
echo "not registered";
}elseif($query == 1){
echo "registered"
}
If I'm not wrong, the query is suppose to return 0 or 1 and it works in my SQLite manager. What is the correct way on getting that value in Php and use it in IF ELSE statement?
If you only need a single value, you can use querySingle:
$result = $database->querySingle("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID'");
Otherwise, with normal queries, the result returned by ->query isn't actually the data itself, but an identifier you would use to get data from the database:
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}

How to count rows from a Mysql result?

i have tried alot and this is my last code. Any ideas how i can get this work?
$id_name = $this->name->Text;
$finder = prdtblRecord::finder();
$result = $finder->findAllByname($id_name);
$row_cnt = $result->num_rows;
You can create a query that checks if the id you have exists or not
$sql = "SELECT EXISTS(SELECT * FROM YOUR_TABLE_NAME WHERE id = TO_CHECK_ID )"
then you could do something like
$id = mysql_query($sql);
if($id)
echo "success"; //your code upon success
else
echo "failed"! //your code upon failure
hope this helps

Create single PHP Function for similar queries but with different WHERE clauses

I'm not sure if this is doable or not, and I'm not entirely sure how to search for this. I have several dynamic web pages that all link to the same MySQL database table, but pull different results. So for example, a dynamic web page with ID = 5 will run a query like:
SELECT * FROM myTable WHERE category1 = 1
The web page where ID = 7 will run:
SELECT * FROM myTable WHERE category2 = 1
And so on. The queries are all grabbing the data from the same table, but the WHERE clause is different for each query - its not looking at the same column. The page with ID 7 should ONLY be returning results where category2 = 1, and ignoring the results that would be returned for the page with id = 5. My website has about 20 different pages/queries like this which is why I'm looking to see if it can be done in a function instead.
Is there a way I can put that into a function, and if so, how would I set up the parameters correctly? Or is this an instance where I will have to just write out all the queries separately on each page?
function find_results(what to put here?) {
global $connection;
$query = "SELECT * FROM myTable WHERE (how to code this part?)";
$result = mysqli_query($connection, $query);
confirm_query ($result);
return $result;
}
You would add the necessary parameters to your functions argument list, then provide the values at runtime.
function find_results($column, $value)
{
global $connection;
$query = "SELECT * FROM myTable WHERE {$column} = $value";
$result = mysqli_query($connection, $query);
confirm_query ($result);
return $result;
}
//Usage:
$result = find_results("category2", 1)
If the value you are returning records by ever ends up being a string make sure your wrap $value in single quotes.
if its a constant relation between pageId and categoryId, you can just create an array to hold it indexed by pageId like:
$pageIdToCategoryMapping = [
1 => 'cateogory1',
2 => 'category5',
...
]
and then just use it to pass data to your function like
find_results($pageIdToCategoryMapping[$pageId])
function find_results($category) {
(...)
$query = "SELECT * FROM myTable WHERE ({$category} = 1)";
(...)
}
I have been using class and object methods for mysql operations. source code available in github
I would recommend you to pass array as an argument and can return query or result as array in format you required. And this function will work any number or condition
<?php
$arg['db']="database";
$arg['tabe']="table";
$arg['search']['id1']="id1";
$arg['search']['id2']="id2";
//
function searchAndReturnResultAsArray($arg)
{
$return = NULL;
$query="SELECT * FROM ".$arg['table'];
$flag=false;
foreach($arg['search'] as $key=>$value)
{
if($flag)
$query.=" AND ";
else
$flag=true;
$query.= $key." = '".$value."' ";
}
$row = mysqli_num_rows($query);
$field = mysqli_fetch_object($query);
if($row >= 1)
{
while($data = mysqli_fetch_array())
{
$return[] = $data;
}
}
return $return;
}
?>
Or alternatively you can just return query once it is ready.

How to insert where condition in mysql query

I will pass the query into this function query("SELECT * FROM table_name");
And the function is
public function query($sql) {
$resource = mysql_query($sql, $this->link_web);
if ($resource) {
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
mysql_free_result($resource);
$query = new stdClass();
$query->row = isset($data[0]) ? $data[0] : array();
$query->rows = $data;
$query->num_rows = $i;
unset($data);
return $query;
} else {
return true;
}
} else {
trigger_error('Error: ' . mysql_error($this->link_web) . '<br />Error No: ' . mysql_errno($this->link_web) . '<br />' . $sql);
exit();
}
}
I want to add tenent_id = '1' in SELECT query also for INSERT query. Likewise I need to do it for UPDATE.
I want to bring the query like this
SELECT * FROM table_name WHERE tenent_id = 1 and user_id = 1
INSERT INTO table_name('tenant_id, user_id') VALUE('1','1')
UPDATE table_name SET user_id = 1 WHERE tenant_id = '1'
Can anyone give me the idea about how to insert tenant_id in select, insert and update
Thanks in advance
It's better practice to use the correct mysql functions rather than just a query function.
For example, if you want to cycle through many items in a database, you can use a while loop:
$query = mysql_query("SELECT * FROM table WHERE type='2'");
while($row = mysql_fetch_array($query)){
echo $line['id'];
}
This would echo all the IDs in the database that have the type 2.
The same principle is when you have an object, using mysql functions, you can specify how you want the data to return. Above I returned it in an array. Here I am going to return a single row as an object:
$query = mysql_query("SELECT * FROM table WHERE id='1'");
$object = mysql_fetch_object($query);
echo $object->id;
echo $object->type;
echo $object->*ANY COLUMN*;
This would return as:
1.
2.
Whatever the value for that column is.
To insert your data, you don't need to do "query()". You can simple use mysql_query($sql).
It will make life much easier further down the road.
Also, its best to run one query in a function, that way you can handle the data properly.
mysql_query("INSERT...");
mysql_query("UPDATE...");
mysql_query("SELECT...");
Hope this helps.
The simple answer is: just add the condition to your query. Call query("SELECT * FROM table_name WHERE tenant_id = 1 and user_id = 1").
If you're concerned about escaping the parameters you pass to the SQL query (which you should be!), you can either do it yourself manually, e.g.
$query = sprintf("SELECT * FROM table_name WHERE tenant_id = %d", intval($tenant_id));
query($query);
Or better use prepared statement offered by mysqli extension (mysql_query is deprecated anyway):
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE tenant_id = ?");
$stmt->bind_param("i", $tenant_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// ...
}
If I still haven't answered your question, you can use a library to handle your queries, such as dibi:
$result = dibi::query('SELECT * FROM [table_name] WHERE [tenant_id] = %i', $id);
$rows = $result->fetchAll(); // all rows
The last option is what I would use, you don't need to write your own query-handling functions and get query parameter binding for free. In your case, you may utilize building the query gradually, so that the WHERE condition is not part of your basic query:
$query[] = 'SELECT * FROM table_name';
if ($tenant_id){
array_push($query, 'WHERE tenant_id=%d', $tenant_id);
}
$result = dibi::query($query);

php functions within functions

ihave created a simple project to help me get to grips with php and mysql, but have run into a minor issue, i have a working solution but would like to understand why i cannot run this code successfully this way, ill explain:
i have a function,
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
this fetches all the movies in my db, then i wish to get the count of actors for each film, so i pass in the get_actors($id) function which gets the movie id and then gives me the count of how many actors are realted to a film.
here is the function for that:
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
the functions both work perfect when called separately, i just would like to understand when i pass the function inside a function i get this warning:
Warning: mysqli_fetch_array() expects
parameter 1 to be mysqli_result,
boolean given in
/Applications/MAMP/htdocs/movie_db/includes/functions.inc.php
on line 287
could anyone help me understand why?
many thanks.
mysqli_query failed to run your query:
Returns FALSE on failure. For
successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will
return a result object. For other
successful queries mysqli_query() will
return TRUE.
Before running mysqli_fetch_array test $result... Something like:
if ($result !== false)
$row = mysqli_fetch_array($result);
else
return false;
Seems like a variable scope issue within your SQL statement. Outputting the SQL should show you the "true" error.
You may want to try using classes with your functions, for example:
class getInfo {
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
}
$showInfo = new getInfo;
//fetch all movies
$showInfo->fetch_all_movies();
//List actors from movie 1
$showInfo->get_actors("1");
In case of an error mysqli_query will return false. You have to handle the error a simple way to do this might be:
$result = mysqli_query($connection,$query);
if (!$result) {
die(mysqli_error($connection));
}
$row = mysqli_fetch_array($result);
Please note that terminating (by doing die() ) usually is no good way to react on an error, log it, give the user anice error page etc. It's alsonogood practice to give the low level error message toauser, this might motivate users to try to exploit a possile security issue.
Last remark: you were writing
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
you should properly escape the movieId there.

Categories