PAssing PHP variables inside a mysql_query function - php

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.

Related

How to find month wise data from mysql in CI

Just a small quick question,
I want to form the query like this
SELECT *
FROM users
WHERE MONTH( `birthday` ) = MONTH( '1999/05/19' )
Now while in my PHP function, I wants to perform same but I am getting this from post variable , after forming the query my output is like this:
SELECT *
FROM `users`
WHERE MONTH(birthday) = 'MONTH(\"1999-05-19\")'
I want to remove \ from code.
My Code for the following is :
$birthday = $this->input->post('birthday');
$where['MONTH(birthday)'] = 'MONTH('.'"'.$birthday.'"'.')';
$result = $this->User_model->getAnyData($where);
Can anyone tell me where I am going wrong?
use like given below may help you
$birthday = $this->input->post('birthday');
$where['MONTH(birthday)'] = "MONTH(".$birthday.")";
$result = $this->User_model->getAnyData($where);
If the POSTed data contains backslashes, use PHP's stripslashes() to remove them: http://php.net/manual/en/function.stripslashes.php.
Depending whether your string was enclosed by single or double quotes will depend on what you do:
<?php
$sql = 'SELECT *
FROM `users`
WHERE MONTH(birthday) = MONTH("1999-05-19")';
Should work. Also:
<?php
$sql = "SELECT *
FROM `users`
WHERE MONTH(birthday) = MONTH('1999-05-19')";
To remove the single quote, you need to pass false paramete in active record.
$this->db->where('MONTH(birthday)', 'MONTH(YOUR_DATA)', FALSE);
So the query would be like:
$this->db->select('*');
$this->db->from('TABLE_NAME');
$this->db->where('MONTH(birthday)', 'MONTH(YOUR_DATA)', FALSE);
Try with this,Fetching only month.
$birthday = $this->input->post('birthday');
$birthday = DateTime::createFromFormat('d/m/Y', $birthday)->format('m');
$where['MONTH(birthday)'] = $birthday;
$result = $this->User_model->getAnyData($where);
SELECT * FROM users WHERE MONTH( `birthday` ) = '05 ';
DISPLAY MONTH WISE DATA WITH PHP CODEIGNITER
$query = $this->db->query("SELECT COUNT(id) as count,MONTHNAME(created_at) as month_name FROM users WHERE YEAR(created_at) = '" . date('Y') . "'
GROUP BY YEAR(created_at),MONTH(created_at)");
$record = $query->result();
$output = [];
foreach($record as $row) {
$output[] = array(
'month_name' => $row->month_name,
'count' => floatval($row->count)
);
}
$data['output'] = ($output);

PHP MySQL with two query

I need to do a SELECT * FROM table_X , the problem is table_X is the result of another query, I don't know how to do it, perhaps with two loop, something like this :
<?php
$query1 = mysql_query("SELECT * FROM table_ref");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query(" SELECT * FROM '$name' ");
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
?>
The tables are all similar & I can't do joint there's no keys. So what I want is to show only the results of the second query from each results of the first query !
So, what's your structure? I don't understand. You have column table_name where are listed a lot of tables? If so, just use backquotes on your $name:
$query2 = mysql_query(" SELECT * FROM `$name` ");
Apart from the obvious that has been pointed out in the comments, you're overwriting $row in the second loop.
Also, you're trying to read an array ($data) that is not defined.
The following will work much better (but still isn't ideal):
$query1 = mysql_query("SELECT `table_name` FROM `table_ref`");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query("SELECT `itime` FROM `$name`");
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
just change your quotes to have the query ready to be started
change
$query2 = mysql_query(" SELECT * FROM '$name' ");
to
$query2 = mysql_query(" SELECT * FROM `".$name."` ");
i would also rather sugest to check this part
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
you already used variable $row to fetching previus query so better to change to something else, look like $data is matching your needs because you already used but you did not declare it
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
Try this query:
select x.* from ( SELECT table_name FROM table_ref) as x

Short Code for PHP string with variable

I have a query string that contains a variable like this
$field_name = 'features';
$value = '5';
$query = "SELECT * FROM Table WHERE $field_name\_tid = '$value'";
My goal is to print out the $query like this SELECT * FROM Table WHERE features_tid = '5';
I put \_ there hoping it would work as escape character, but it didn't work. Is there any way to achieve this without use methods like ". $field_name ." and modifying original variable value?
yes:
$query = "SELECT * FROM Table WHERE {$field_name}_tid = '$value'";
You can use:
$query = "SELECT * FROM Table WHERE {$field_name}_tid = '$value'";

PHP variables in WHERE clause, how to?

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.

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