COUNT always returning 1 - php

I have issue where obj->num_rows constantly returns 1 Heres my code:
$open_tickets = $con->query("SELECT COUNT(*) FROM support_tickets WHERE Username='" . $_SESSION['user'] . "'");
echo '<table><tr><th>Open Tickets</th><td>' . $open_tickets->num_rows . '</td></tr></table>';
$open_tickets->close();
$_SESSION['user'] is currently dextermb
As you can see in my SQL table, there are 2 tickets with the name dextermb, so why does the code always return 1?

You are getting the number of rows returned - of course, this is only ever going to be 1. You probably want to get the value that is returned rather than the number of rows.

Try this
$open_tickets = $con->query("SELECT * FROM support_tickets WHERE Username='" . $_SESSION['user'] . "'");
echo '<table><tr><th>Open Tickets</th><td>' . count($open_tickets) . '</td></tr> </table>';
$open_tickets->close();

The query will return the count, just use the value.
Try:
$open_tickets = $con->query("SELECT COUNT(*) FROM support_tickets WHERE Username='" . $_SESSION['user'] . "'");
echo '<table><tr><th>Open Tickets</th><td>' . $open_tickets . '</td></tr></table>';
$open_tickets->close();

Try this:
$stm = $con->prepare("SELECT COUNT(*) as total FROM support_tickets WHERE Username = :username");
$stm->bindParam(':username', $_SESSION['user']);
$stm->execute();
$row = $res->fetch();
echo '<table><tr><th>Open Tickets</th><td>' . $row->total . '</td></tr></table>';
Note prepare and bindParam methods. This way you avoid SQL Injection.

Related

Retrieving data belonging to a session and user id

I am trying to obtain data from the current session and the field "bidder_id" from tbl_bidder where the field "accept" has the value Accepted, but I get data of all the users in that table which is not I want. This is my code
<?php } else if (($_SESSION['Usertype']) == 'recruiter') { ?>
<table class="table table-hover">
<?php
$u_id = $_SESSION['UserID'];
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "'";
$ResultR = mysql_query($notifyR, $con);
while ($rowR = mysql_fetch_array($ResultR)) {
if ($rowR['accept'] == "Accepted") {
echo "<h3 style='color:#001F7A;'><b>You Have Updates </b><i class='fa fa-bell-o'></i></h3>";
echo $rowR['bidder_id'];
}
$recR = "SELECT users_id, first_name, last_name FROM tbl_users WHERE users_id = '" . $rowR['bidder_id'] . "'";
$recResultB = mysql_query($recR, $con)or die(mysql_error());
while ($rowre = mysql_fetch_array($recResultB)) {
echo " <tr><td>" . $rowre['first_name'] . " " . $rowre['last_name'] . "</td></tr>";
}
}
?>
Please help!!!
Change From
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "'";
To
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "' and accept = 'Accepted' ";
add this on your query and accept = 'Accepted' in $notifyR
I hope you might need to use the following query if you stored the user id in $_SESSION['UserID']. May be logical error: And also use mysqli_query instead of mysql_query which is deprecated in latest php versions. And instead of binding the variable directly in query, use bind param of prepared statement.
$recR = "SELECT users_id, first_name, last_name FROM tbl_users WHERE users_id = '" . $_SESSION['UserID'] . "' LIMIT 1";
If you only want to execute the second query (selecting the user associated with the given bid) when the bid has been "accepted" then you need to move that code into your conditional:
if ($rowR['accept'] == "Accepted") {
echo "<h3 style='color:#001F7A;'><b>You Have Updates </b><i class='fa fa-bell-o'></i></h3>";
echo $rowR['bidder_id'];
$recR = "SELECT users_id, first_name, last_name
FROM tbl_users
WHERE users_id = '" . $rowR['bidder_id'] . "'";
$recResultB = mysql_query($recR, $con)or die(mysql_error());
while ($rowre = mysql_fetch_array($recResultB)) {
echo " <tr><td>" . $rowre['first_name'] . " " . $rowre['last_name'] . "</td></tr>";
// echo $rowre['users_id'];
}
}
You may want to consider using a newer interface to MySQL, such as PDO, and protecting your code from SQL injection attacks by using techniques such as prepared statements or at least input cleansing.

Selecting data of a 'person'' using LIMIT from table

I was wondering how to fetch data of a person from a table. I found the query to LIMIT data fetch from table. Here is what I got so far:
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
It returns data when LIMIT is available but if the LIMIT exceed the entire data returns null. So how can I know if ROW is available or not in table?
use mysql Count
SELECT count(username) FROM users WHERE username ='xyz'
And your $last_limt is not grater than total count-1
You have to check number of rows of the result from that query before proceeding
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
$rowcount=mysql_num_rows($result);
if($rowcount > 0)
{
//next operations
}
else
{
//No more data
}

MySQL does not retrieve first item in PHP

I've now been trying for hour and can't figure the problem out. I've made a php file that fetch all items in a table and retrieves that as JSON. But for some reason after I inserted the second mysql-query, it stopped fetching the first item. My code is following:
...
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
$row2 = $result2->fetch_assoc();
while($row = $result2->fetch_assoc()) {
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,
strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
Any help is greatly appreciated.
EDIT: Thanks for all those super fast responses.
First you're fetching a row:
$row2 = $result2->fetch_assoc();
Then you start looping at the next row:
while($row = $result2->fetch_assoc()) {
If you want to loop over all of the rows, don't skip the first one. Just loop over all of the rows:
$result2 = // your very SQL-injectable query
while($row2 = $result2->fetch_assoc()) {
$result3 = // your other very SQL-injectable query
$row3 = $result3->fetch_assoc();
// etc.
}
Note that errors like this would be a lot more obvious if you used meaningful variable names. "row2", "result3", etc. are pretty confusing when you have overlapping levels of abstraction.
Important: Your code is wide open to SQL injection attacks. You're basically allowing users to execute any code they want on your database. Please look into using prepared statements and treating user input as values rather than as executable code. This is a good place to start reading, as is this.
No Need of $row2 = $result2->fetch_assoc();
<?
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
while($row = $result2->fetch_assoc())
{
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
?>
Or,
<?
...
case "LoadEntryList":
$Category=$_POST["Category"];
$Offset=$_POST["Offset"];
$Quantity=$_POST["Quantity"];
$result3 = performquery("SELECT Entries.*, Users.Username FROM Entries, Users WHERE Entries.Category=$Category AND Entries.UserID=Users.ID LIMIT $Offset, $Quantity");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
?>
I have a addition to David answer(can't comment on it yet)
This line of code:
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
will always return with the same result. If you were to change $row2[... into $row[... the code would take the rows that get updated by the while loop.
I am not content with the accepted result. The snippet can be fixed / replaced, and also a bad code must be replaced. Also not to mention is that I don't know if anyone spotted a really big mistake in the output. Here is the fix and I'll explain why.
$JSON = array();
$result2 = performquery( '
SELECT
e.*, u.Username
FROM Entries AS e
LEFT JOIN Users AS u ON u.ID = e.UserID
WHERE
e.Category = ' . $_POST['Category'] . '
LIMIT ' . $_POST['Offset'] . ', ' . $_POST['Quantity'] . '
' );
while( $row2 = $result2->fetch_assoc() ){
$JSON[] = $row2;
}
echo json_encode( $JSON );
Obviously the main issue is the query, so I fixed it with a LEFT JOIN, now the second part is the output. First it's the way you include the username, and the second what if you had multiple results? Than your output will be:
{"ID":1,"Username":"John"}{"ID":2,"Username":"Doe"}
How do you parse it? So the $JSON part comes in place. You add it to an array and will encode that array. Now the result is:
{["ID":1,"Username":"John"],["ID":2,"Username":"Doe"]}
LE: I left out the sql inject part which as stated by the OP, will be done afterwards? I'm not sure why not do it at the point of writing it, because you may forget later on that you need to sanitize it.

Update a sql table field one time with php

Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}

PHP checking if query returns anything error

I've been pondering about this for a while, I'm trying to see if the query wields any results and I want to do something if it doesn't return any results.
PHP:
<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "";
$con = mysql_connect($host, $user, $passw);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$json = $_REQUEST['json'];
$json = stripslashes($json);
$jsonobj = json_decode($json);
$me = $jsonobj -> me;
$other = $jsonobj -> other;
mysql_select_db("tinyspace", $con);
$result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')");
if(mysql_num_rows($result) > 0)
{
}
the if statement keeps giving me problems however.
Any Advice?
just to be sure, how many columns do you have named userid? user_id, user_id1, user_id2 ?
do you mean user_id1 in place of user_id in the below line, by any chance?
$result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')");
If so, maybe thats why you aren't fetching any results.
Edit:
$result = mysql_query("SELECT * FROM friends WHERE (user_id1 = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')");
you should try
<?php
if($result == false){
//what you want to do if the query returns nothing
}else{
//handle the result
}
for those who think my answer is incorrect or the opposite of what is asked, please read the question from the beginning again, very carefully.
mysql_num_rows() is okay to use for checking if you have results, and should work in your example..
However, if your call to mysql_num_rows() doesn't work as expected (i.e. always false), it's almost always down to a problem with the query.
mysql_num_rows() expects a result resource, and if there is a problem with your query, mysql_query will return a false.
You can amend your mysql_query() call to
mysql_query("sql here") or die(mysql_error());
That should give you an idea if the error lies in the query. Once you've checked your query is working as expected, your mysql_num_rows() will start functioning correctly.
Additionally, the mysql_ functions are depreceated, you should take a look at Prepared Statements http://php.net/manual/en/pdo.prepared-statements.php
$result = mysql_query("SELECT * FROM `friends` WHERE (`user_id1` = '" .$me. "' AND `user_id2` = '" .$other. "') OR (`user_id2` = '" .$me. "' AND `user_id1` = '" .$other. "')");
to simply answer your question, while it seems that while your code is potentially vulnerable, it should act as you intend. This is what I use in my connection class
public function makeQuery(){
if($result = mysqli_query($this->link, $this->sql)){
if(mysqli_num_rows($result) != 0){
while($r = mysqli_fetch_array($result)){
$return[] = $r;
}
mysqli_free_result($result);
return $return;
}else{
return 0;
}
}else{
// db error here
}
}
This assumes you feed the class some value for $sql and $link... but you can then check for either an integer return or an array return. if it is an integer (0), it had no rows, an array will be the returned rows. If there is an error it will fall into the error logic (I send myself an email in this case).

Categories