I'm trying to print out only the number of rows containing user2_ids within my streamdata_feedback table and it seems to be printing out both the user2_id and the user1_id. How can I rectify this issue with the below code?
$user1_id=$_SESSION['id'];
$user2_id=$data['id'];
$likesqltwo = "SELECT *
FROM streamdata_feedback
WHERE feedback_rating = 1
AND feedback_userid = " . $user2_id .
"AND feedback_streamid = " . $streamid;
$likequerytwo = mysql_query($likesqltwo);
$num3 = mysql_num_rows($likequerytwo);
if ($num3 > 0)
{
echo "And <a title = 'See who likes " .
$poster_name['fullusersname'] .
"s status' href='include/likes.php?streamitem_id=" .
$streamitem_data['streamitem_id']."' />" .
$num3 . " ";
}
Do you have a client for your MySQL database? I'd recommend picking up SqlYog Community Edition. You can then execute your query against it and see how many rows are returned outside of PHP code. Once you have a satisfactory query, then incorporate it into your PHP project.
Next tip: You can include variables from PHP directly in strings with double quotes. PHP will parse the variable, and you needn't concatenate. For example:
$likesqltwo =
"SELECT *
FROM streamdata_feedback
WHERE feedback_rating = 1
AND feedback_userid = $user2_id
AND feedback_streamid = $streamid;";
However this code still has a potential flaw, and that's SQL injection attacks. So ensure that the variables you include are not coming from users, or follow the link to learn more about preventing such things. That's not what you asked for help on, but I thought it was worth a mention.
To find out how many times the feedback_userid equals $user2_id for a particular feedback_streamid and for only feedback_rating values of 1, you could try the following query:
SELECT COUNT(id)
FROM streamdata_feedback
WHERE feedback_rating = 1
AND feedback_userid = 123
AND feedback_streamid = 456;
Substitute your primary key for id, and the correct user id and stream id for 123 and 456 respectively. If you get an unexpected number of results, I recommend removing COUNT(id) and selecting the columns of interest so you can inspect and see why you're getting more rows than you thought.
Related
Sometimes I'm getting this error (on remote server only):
General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll()...
I added this line on top of my php code - without success:
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute;
Two questions:
How to properly avoid this error, if possible without using fetchAll()?
What should I do to get this error on my localhost, if the error exists?
I'm on Windows 7, xampp, phpmyadmin...
here is the code
$st = $db->query("select title from folders where id = " . $_GET['fd'] . " limit 1");
$st->execute();
$title = $st->fetchColumn();
$stb = $db->query("select * from arts where folder = " . $_GET['fd'] . " order by ind asc");
error is on the last line
Simple answer
Create a new (additional) connection.
Once your in the middle of an un-buffered request that connection is locked/block up. Pretty much unusable.
Or don't do it (while the buffered query is on-going).
So if you need to query other things, either do that before the unbuffered part, or open a second buffered (normal) connection to the DB.
I once pulled 140 million rows out of the DB with an un-buffered query. Now they are in MongoDB (even though I have mixed feelings about this). PS. if anyone knows how to improve mongo's count performance I am all ears.
You only really need un-buffered query if your working with a Large dataset, and I mean > 500k rows. I use it as a last resort.
Anyway, good luck. It's a pain.
Update
For you case, you need to make the PDOStatement object go away or call PDOStatement::closeCursor.
$st = $db->query("select title from folders where id = " . $_GET['fd'] . " limit 1");
$st->execute();
$title = $st->fetchColumn();
unset($st); //<---- unset the statement object
$stb = $db->query("select * from arts where folder = " . $_GET['fd'] . " order by ind asc");
If I am thinking about it right, that unset should take care of it. Normally this happens when it goes out of scope such as the end of a method or function and no reference to it. This is sort of like free_result or whatever it was for Mysqli
I just assumed you had something like this:
$st = $db->query("select title from folders where id = " . $_GET['fd'] . " limit 1");
$st->execute();
foreach($st->fetchColumn() as $col){
$stb = $db->query("select * from arts where folder = {$col} order by ind asc");
}
Where you were using the results of an open Query for a new query. Which is a no-no. In a case like above the only thing you can do is open a new connection for the part in the loop as it may not be possible to do it all in one Query (for whatever reason).
In any case change this to proper prepared statements:
$st = $db->prepare("select title from folders where id = :id limit 1");
$st->execute(['id' => $_GET['fd']]);
As it is your vulnerable to SQLInjection. It's very easy to fix in PDO, and it's very bad to not do it.
Cheers!
My problem is that i don't yet have a good server to test this on but i'd like to know if it faster to use:
$sqlgetg = "SELECT assignments.id FROM assignments LEFT JOIN userassignments ON assignments.id = userassignments.assignmentid WHERE userassignments.userid = '" . $row['id'] . "' AND userassignments.assignmentid = '" . $assignmentid . "'";
or
$sqlgetg = "SELECT NULL FROM assignments LEFT JOIN userassignments ON assignments.id = userassignments.assignmentid WHERE userassignments.userid = '" . $row['id'] . "' AND userassignments.assignmentid = '" . $assignmentid . "'";
Since i have to check if there even is an assigment for the user with assignment id of x? I don't need anything else but this: if(mysqli_num_rows($resultgetg) > 0)? In both cases phpMyAdmin gave me the row number that i wanted. (I checked it with
without WHERE and it still worked.)
EDIT:
I don't know how and why NULL works but it does...
You can select any static value "from" a table if you just want to count the rows returned... SELECT NULL or SELECT 42 or whatever. But both of your strategies are in fact suboptimal, because they require unnecessary work by the server and unnecessary network traffic and unnecessary handling of the result set that you are only planning to discard.
If counting rows is what you want, then actually do that. you should SELECT COUNT(*) AS how_many_rows ... and let the server count the rows and return a single row with a single column ("how_many_rows" -- make up your own alias) containing the count.
Below is MySql query:
$queryfilter = "SELECT * FROM tablename where sector = " .$_SESSION['idfilterdrop']. " AND
region IN (SELECT region from
tablename where sector = " . $_SESSION['sector'] ." OR region = " .
$_SESSION['r1'] ." OR theme = " . $_SESSION['theme'] .")";
Help me to find the syntax error. I am sure there is a problem of double quotes in the above query. When I run this query on MySql prompt it runs fine but when I replace the constant value with variables this query doesn't work.
Unfortunately, we don't know if your $_SESSION array contains integers or strings. if the elements sector, r1 or theme are strings, you need to quote them in your SQL, like this: WHERE sector = '". $_SESSION['sector'] . "' OR.
Also, your table being named database does not help. If I recall correctly, DATABASE is a reserved word, so you'll need to put backtics around that table name:
... FROM `database` ...
I'm trying to generate XML from database and need to gather a specific amount of data based on the average from a column. This can vary from anywhere between 5 to 30 queries for the $numItems variable.
I need to execute a for loop and assign the column name in the SUM($variable) but I'm not getting any data (but no errors either).
Here is my code:
for ($t = 1; $t <= $numItems; $t++){
$query = mysql_fetch_assoc(mysql_query("SELECT SUM(column'".$t."') AS value_sum FROM scoring WHERE ID='" . $userID . "' AND name ='" . $name . "'"));
$q = $query['value_sum'] / $totalUsers;
echo "<output".$t.">" . $q . "</output".$t.">\n";
}
The problem is assigning the SUM(column1) variable name for the column I'm getting data from, when I write the queries individually it works, but assigning the variable within the statement is causing a problem. Can any one give me any pointers?
Thanks in advance.
It looks like you might have extra single quotes in your query. I think it should be:
"SELECT SUM(column".$t.")..."
You should also consider doing a single select. Doing multiple database calls inside a for loop will be a huge performance problem. You could write a single select like this:
"SELECT SUM(column1), SUM(column2), SUM(column3),..."
Looks like bad escaping/concatenation around the column name...
"SELECT SUM(column{$t}) AS value_sum FROM scoring WHERE ID='{$userID}' AND name ='{$name}'"
Is that what you want?
Also use PDO!
I'm trying to order my blog posts by user defined category, i.e, the one they click on my blog page.
Here's my code thus far,
##########################################################
$cat = mysql_real_escape_string($_GET['category']);
##########################################################
$sql = "SELECT * FROM php_blog WHERE category = $cat ORDER BY timestamp";
$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());
But that gives me this error,
Can't select entry from table
php_blog. SELECT * FROM php_blog WHERE
category = Update ORDER BY timestamp
You have an error in your SQL syntax;
check the manual that corresponds to
your MySQL server version for the
right syntax to use near 'Update ORDER
BY timestamp' at line 1 Warning:
mysql_fetch_array(): supplied argument
is not a valid MySQL result resource
in
/home/funding9/public_html/jbblog/htdocs/category.php
on line 91
$sql = "SELECT * FROM php_blog WHERE category = '" . mysql_real_escape_string($cat) . "' ORDER BY timestamp";
The string needed to be quoted (in your example it was Update, needs to be 'Update'), and also I ran it through mysql_real_escape_string() to protect you from SQL Injection.
MySQL uses back ticks to allow you to escape names. You should be using something like the following:
$cat = mysql_real_escape_string($_GET['category'], $mysql_link);
$queryString = "SELECT * FROM `php_blog` WHERE `category` = '$cat' ORDER BY `timestamp`";
Supplying the link will make sure it is escaped for that connection, where different databases may have different configurations and require different things to be escaped in them.
You may also want to look into the use of prepared statements with MySQLi as well. That takes the difficulty out of knowing which input needs to be escaped, how it should be quoted and even some of the verification.