how to do sql query check if empty without useing php - php

In this SQL query I select by id was set in the session but at some cases there is no found any id match the field in the table, so I put if/else statement with mysql_num_rows function to avoid error message...
So my question is: Is thre any SQL code to check if is there is value or not without using mysql_num_rows function?
SELECT *
, d_articles.ar_id
, d_articles.ar_article_title
, d_articles.ar_article_desc
, d_articles.ar_created
, d_articles.ar_link_img
, d_articles.ar_img
FROM
d_articles
WHERE
d_articles.ar_hide = 1 AND
d_articles.ar_category_id ='" . $this->session->userdata('branch_id') . "'
ORDER BY
ar_created desc limit 1

<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
FOR SQL QUERY:
$tsql = "SELECT ProductID, Name, Color, Size, ListPrice
FROM Production.Product
WHERE Name LIKE '%' + ? + '%' AND ListPrice > 0.0";
$params = array( $_REQUEST['query'] );
$getProducts = sqlsrv_query( $conn, $tsql, $params);
if ( $getProducts === false)
{ die( FormatErrors( sqlsrv_errors() ) ); }
READ MORE

Related

Wordpress: wpdb prepare with conditional variable

I currently have a table. If the user searches for something, I would like the query to return the filtered results. If the user doesn't search for something, it should return all results. I'm not too sure how to do this with wpdb prepare.
if($search_query!=="all") {
$search_query = '%' . $search_query . '%';
$where = 'WHERE column_name LIKE %s';
}
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_name ".$where." ORDER BY id DESC LIMIT %d, %d", $search_query,$current_page,$rows_per_page));
Right now nothing returns when the search field is empty because the query is erroring out because it's throwing the parametrization off and passing $search_query to the %d beside LIMIT. Is it possible to make this variable conditional? Is there a way to do this without an IF statement ?
It looks like you can pass an array to prepare, as well as a list of variables, according to the WordPress documentation
That means that you could do something like this:
$where = "";
$parameters = array($search_query,$current_page,$rows_per_page);
if($search_query!=="all") {
array_push($parameters, '%' . $search_query . '%');
$where = 'WHERE column_name LIKE %s';
}
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_name ".$where." ORDER BY id DESC LIMIT %d, %d", $parameters));
Your WHERE clause will be empty if there's no data, so concatenating it into your query won't cause issues.
Why not do the prepare in the "If" statement? You can then do the other prepare (without the where clause) in the "Else" and just use the get_results on the proper prepared query?
if($search_query!=="all") {
$search_query = '%' . $search_query . '%';
$where = 'WHERE column_name LIKE %s';
$prepared = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_name ".$where." ORDER BY id DESC LIMIT %d, %d", $search_query, $current_page, $rows_per_page) ;
} else {
$prepared = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_name ORDER BY id DESC LIMIT %d, %d", $current_page, $rows_per_page);
}
$results = $wpdb->get_results($prepared);
You can escape the like parameter yourself and add it as a where clause if needed like this:
function like($str)
{
global $wpdb;
return "'" . '%' . esc_sql($wpdb->esc_like($str)) . '%' . "'";
}
if($search_query!=="all") {
$where = 'WHERE column_name LIKE ' . like($search_query);
}
and remove the search_query param from the prepared statement

LIKE query is unable to retrieve data, why?

This query is unable to retrieve any data from MySQL for reasons I cannot figure out after countless hours..
public function search()
{
if(isset($_GET['search']))
{
$searchTerms = trim(strip_tags($_GET['search']));
$sth = $this->db->prepare("SELECT COUNT(*) FROM articles WHERE (article_content LIKE :search) OR (article_title LIKE :search)");
$sth->execute( array(':search' => '%' . $searchTerms . '%') );
if($sth->fetchColumn() > 0)
{
while($row = $sth->fetchAll(PDO::FETCH_ASSOC))
{
return "search results: " . $row['article_title'];
return "" . $row['article_content'];
}
} else {
echo "No results.";
}
}
}
No matter what keyword I type in the form it always returns "No results.". What could be the issue because from what I can see it should work..
Selecting all rows from the table structure and counting so that fetchColumn can be runned, it is selecting from the correct table (articles), where article_content and article_title are both rows in the table, so what is the issue?
$sth->execute(array(':search' => '%'.$searchTerms.'%'));
Should be:
$sth->execute(array(':search' => '\'%\' + \''.$searchTerms.'\' + \'%\''));
Each bind var needs to be an individual bind var, even when named, and even when they both contain the same value:
$sth = $this->db->prepare(
"SELECT COUNT(*)
FROM articles
WHERE (article_content LIKE :search1)
OR (article_title LIKE :search2)"
);
$sth->execute(
array(
':search1' => '%' . $searchTerms . '%',
':search2' => '%' . $searchTerms . '%'
)
);
Try this:
$sth = $this->db->prepare("SELECT COUNT(*) FROM articles WHERE (article_content LIKE :search0) OR (article_title LIKE :search1)");
$searchstring="%" . $searchTerms . "%";
$sth->execute( array(':search0' =>$searchstring ,':search1'=>$searchstring) );
pdo fails to retrieve values when the same placheholder is repeated in a query with LIKE in it.

PHP and mysqli: Select with multiple conditions using prepared statements

I'm working on some prepared statements using mysqli in a php file with a database running on InnoDB. Most of the statements are working pretty well, but I have a select statement with multiple conditions that keeps returning a syntax error in my select statement, to be specific: near ? AND section_num = ? AND dept = ? AND semester = ? AND year = ? at line 1 as well as the following error:
Call to a member function bind_param() on a non-object.
Here's the snippet of code:
if (!$rs = $mysqli->query("SELECT id FROM courses WHERE course_num = ? AND section_num = ? AND dept = ? AND semester = ? AND year = ?")) {
echo "Select Query Failed!: (" . $mysqli->errno . ") ". $mysqli->error;
}
if(!$rs->bind_param("ssssi", mysqli_real_escape_string($mysqli,$course_num), mysqli_real_escape_string($mysqli,$section_num),
mysqli_real_escape_string($mysqli,$dept), mysqli_real_escape_string($mysqli,$semester), mysqli_real_escape_string($mysqli,$year))) {
echo "Select Binding parameters failed: (" . $rs->errno .") " . $rs->error;
}
if (!$rs->execute()) {
echo "Execute select failed: (" . $rs->errno . ") " . $rs->error;
}
Any suggestions for how to form this statement to retrieve an id based on the 4 inputs would be great. Thanks!
You should be using prepare to prepare a statement, not query as that just executes a query.
$query = "
SELECT id
FROM courses
WHERE
course_num = ? AND section_num = ? AND dept = ? AND semester = ? AND year = ?
";
$rs = $mysqli->prepare($query);
$rs->bind_param("ssssi", $course_num, $section_num, $dept, $semester, $year);
$rs->execute();
Change: $mysqli->query("SELECT id ...
To: $mysqli->prepare("SELECT id ...
It is quite simple just do this
$query = "SELECT * FROM `$table_tran` WHERE `$mem_id` ='$member_id' and $status` = '$cur_status'";
$result = mysqli_query($link,$query);
It gets the data from the transaction table using the and statement.

MySQL - Select differently

I have this query, which selects a distinct value for a column, but I need something else in that query too. I need it to fetch a different row associated with the main select.
Let me illustrate...
This is my query:
$sql = 'SELECT DISTINCT user_id FROM ' . DONATION_SECURITY_TABLE;
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
mysql_free_result($result);
return $rows;
As you see it returns this query returns the DISTINCT of user_id.
If I use a function like this in a double foreach loop created using the return of the query above:
public function get_donor_status($user_id)
{
global $db;
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$payment_status = $row['payment_status'];
$db->sql_freeresult($result);
return $payment_status;
}
This function would return Completed for user_id 2, but I want it to say Pending instead. How would I change my query so it returns the last value for the corresponding user_id?
If I'm not clear enough, please let me know so I can reexplain.
Just select the last row for the user:
"SELECT payment_status FROM " . DONATION_SECURITY_TABLE . " WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1"
How about this?
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1";
You can actually get everything in one SQL statement, no need for a double loop:
SELECT
user_id, payment_status
FROM
DONATION_SECURITY_TABLE t1
WHERE
donation_id = (select max(donation_id) from DONATION_SECURITY_TABLE t2 WHERE t2.user_id = t1.user_id)
ORDER BY
user_id

php - disconnecting and connecting to multiple databases

I want to be able to switch from the current db to multiple dbs though a loop:
$query = mysql_query("SELECT * FROM `linkedin` ORDER BY id", $CON ) or die( mysql_error() );
if( mysql_num_rows( $query ) != 0 ) {
$last_update = time() / 60;
while( $rows = mysql_fetch_array( $query ) ) {
$contacts_db = "NNJN_" . $rows['email'];
// switch to the contacts db
mysql_select_db( $contacts_db, $CON );
$query = mysql_query("SELECT * FROM `linkedin` WHERE token = '" . TOKEN . "'", $CON ) or die( mysql_error() );
if( mysql_num_rows( $query ) != 0 ) {
mysql_query("UPDATE `linkedin` SET last_update = '{$last_update}' WHERE token = '" . TOKEN . "'", $CON ) or die( mysql_error() );
}else{
mysql_query("INSERT INTO `linkedin` (email, token, username, online, away, last_update) VALUES ('" . EMAIL . "', '" . TOKEN . "', '" . USERNAME . "', 'true', 'false', '$last_update')", $CON ) or die( mysql_error() );
}
}
mysql_free_result( $query );
}
// switch back to your own
mysql_select_db( USER_DB, $CON );
It does insert and update details from the other databases but it also inserts and edits data from the current users database which I dont want. Any ideas?
Never use the php mysql_select_db() fundtion - as you've discovered the code (and the coder) gets very confused very quickly.
Explicitly state the DB in the queries:
SELECT * FROM main_database.a_table....
UPDATE alternate_db.a_table SET...
REPLACE INTO third_db.a_table...
C.
You're probably have wrong database design.
one improve that i see is that you can use one query to duplicate or update
the syntax is like :
INSERT INTO mytable (field_list.....) VALUES (values_list...)
ON DUPLICATE KEY
UPDATE field1 = val1 ...
you are reassigning $query during your while loop. this will give strange results. use $query2 for the query inside the loop

Categories