PHP variables in WHERE clause, how to? - php

I have following PHP script. I want to count and print comments for each article.
The id for each article can be "recalled" by this: <?php echo $listing['Listing']['listing_id'];?> (this return the contentid number)
Now, I have this script:
<?php
$db =& JFactory::getDBO();
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ????? ";
$db->setQuery($query);
$count = $db->loadResult();
echo ($count); ?>
I tried to add in WHERE clause this:
"... WHERE contentid = {$listing['Listing']['listing_id']}"
but $count returns "0" zero.
How can I add this variable in the WHERE clause?
Thanks in advance!

In the case of an integer:
$query = "SELECT
COUNT(comments) AS totalcount
WHERE
contentid = " . ((int) $listing['Listing']['listing_id']);
In the case of a string:
$query = "SELECT
COUNT(comments) AS totalcount
WHERE
contentid = " . mysql_real_escape_string($listing['Listing']['listing_id']);
The biggest thing to be weary of is SQL injection. This makes your queries safe. The explicit cast to int will ensure an int value is passed, even if the value is erroneous, at least you wont be open to any attack.

Use sprintf and escape the string.
$query = sprintf("SELECT COUNT(comments) AS totalcount WHERE contentid = '%s'",mysql_real_escape_string($listing['Listing']['listing_id']));

try
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = '".mysql_real_escape_string($listing['Listing']['listing_id'])."'";
or
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ".mysql_real_escape_string($listing['Listing']['listing_id']);
depending on the data type.

Related

PAssing PHP variables inside a mysql_query function

I want to pass a php variable in mysql_query such as:
$tty = '217';
$num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id = '.$tty.'");
$num_of_comments1 = mysql_fetch_array($num_of_comments);
$num_of_comments2 = $num_of_comments1[0];
echo $num_of_comments2 ;
However, I am not able to get the value needed in num_of_comments2. It returns a 0 on echo.
As the colour coding will show you, your query is wrong. You could also debug it by just echoing your query:
SELECT count(*) FROM comments WHERE img_id = '.217.'
Clearly incorrect!
$tty = '217';
$sql = mysql_query("SELECT count(*) FROM comments WHERE img_id = ".intval($tty));
$row = mysql_fetch_row($sql);
$number = $row[0];
echo $number;
Alternative one-liner for getting the value:
list($number) = mysql_fetch_row(mysql_query("select count(*) from `comments` where `img_id`=".intval($tty)));
This should work:
$tty = '217';
$num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id = '".$tty."'");
$num_of_comments1 = mysql_fetch_array($num_of_comments);
$num_of_comments2 = $num_of_comments1[0];
echo $num_of_comments2 ;
Use '".$tty."' instead of '.$tty.'
Basic PHP syntax:
$num_of_comments = mysql_query("[[...snip...]]= '.$tty.'");
You never "closed" your string, so you're trying to execute a PHP concatenation INSIDE your string, which won't work. Your query string is literally going to be
WHERE imd_id = '.217.'
^---^--- note the concatentation operators
For a "-quoted string, you do NOT need to concatenate:
$num_of_comments = mysql_query([[..snip..] = '$tty'");
^^^^^^^---note: no dots
is all you need.

How to select with a binary field ? (php,mysql)

Try to select use "where" clause in a mysql statement:
e.g.
Table: X with a ID column which is BINARY data type. Then save in a variable in php
$aid = $row["id"];
How do i use this variable later when I try to select from table
$where = "where `ID` = '$aid'";
$query = "SELECT * FROM X ".$where;
Return 0 row.
Does anyone know why?
Answering my own question.
Just figured out:
$where = "where HEX(ID) = 'bin2hex($aid)'";
$query = "SELECT * FROM X ".$where;
Does anyone know better solution?
Try below :
add BINARY in where clause.
$where = "where BINARY ID = '$aid'";
$query = "SELECT * FROM X ".$where;

Simple mysql query not working

I have this very simple function:
function getCatName($id){
$sql = "SELECT * FROM biznet_category WHERE ID ='".$id."';";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$name = $row["Name"];
return $name;
}
So with this function I should be able to get the category name, but it doesn't work with the parameter. If I put 8 or 9, the categoryname is displayed correctly.
The id is also passed on like it should, when I print it out, it shows 8 or 9.
I know the solution is quite simple, I just don't see it.
To fix remove the quotes and check the column name for case id or ID. Since the query string is in double quotes you don't have to use the . join
$sql = "SELECT * FROM biznet_category WHERE ID = $id";
You can use curly brackets which I find easier to read
$sql = "SELECT * FROM biznet_category WHERE ID = {$id}";
If you were querying a string rather than an integer you can simply do
$sql = "SELECT * FROM biznet_category WHERE ID = '{$id}'";
$sql = "SELECT * FROM biznet_category WHERE ID ='".$id."';";
To
$sql = "SELECT * FROM biznet_category WHERE ID = ".$id;
Try this
$sql = "SELECT * FROM biznet_category WHERE ID = ".$id;
Is the column name ID spelt correctly?

How to query a database with an array? WHERE = 'array()'

I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!
You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.
Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);

faster mysql query

Is there a faster way to do this?
$data1 = mysql_query(
"SELECT * FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
$num_results = mysql_num_rows($data1);
$data2 = mysql_query(
"SELECT sum(type) as total_type FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
while($info = mysql_fetch_array( $data2 )){
$count = $info['total_type'];
}
$total = number_format(($count/$num_results), 2, ',', ' ');
echo $total;
Cheers!
Looking at your queries, I think you're looking for something like this:
SELECT SUM(type) / COUNT(*) FROM table1 WHERE ...
SELECT COUNT(*) AS num_results, SUM(type) AS total_type FROM table1
WHERE id = $id and type = $type
This single query will produce a one-row result set with both values that you want.
Note that you should use a parameterized query instead of direct variable substitution to avoid SQL injection attacks.
Also, I'm guessing that SUM(type) isn't what you really want to do, since you could calculate it as (num_results * $type) without the second query.
$data1 = mysql_query("SELECT sum(type) as total_type,count(*) as num_rows FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
$info = mysql_fetch_array( $data1 );
$count = $info['total_type'];
$num_results = $info['num_rows'];
$total = ($count/$num_results);
echo $total;
In general: SELECT * can be 'shortened' to e.g. SELECT COUNT(*), if all you care about is the number of matching rows.
One line:
echo number_format(mysql_result(mysql_query("SELECT SUM(type) / COUNT(*) FROM table1 WHRE id = $id AND type = '$type'"), 0), 2, ',', ' ');

Categories