counting rows in php with sql - php

For an application I'm trying to count the total of friends. I want to do this with a function but it isn't returning anything. It tells me this:
Warning: mysqli_query() expects at least 2 parameters, 1 given
But I only need one parameter. I think I'm totally wrong.
This is the function:
public function GetTotalOfFriends($user_id){
$db = new Db();
$select = "SELECT COUNT FROM friendship WHERE (friendship_recipient_id ='" . $user_id ."' OR friendship_applicant_id = '" . $user_id . "') AND friendship_status = 'accepted'";
$result = $db->conn->query($select);
$row = mysqli_query($result);
$total = $row[0];
echo $total;
I'm trying to print it out in this way:
$friend = new Friendship;
$numberoffriends = $friend->GetTotalOfFriends($user_id);
<?php echo $numberoffriends; ?>

You are mixing up a couple of things. The line $result = $db->conn->query($select); already seems to execute a query, but then you try to bypass your database wrapper by passing that query result again to mysqli_query.
Apart from that, I think your query itself is also wrong. COUNT needs a parameter, indicating a field or value to count. Quite often COUNT(*) is used, but COUNT('x') might be more efficient in some cases. You can also use a specific field name, and COUNT will count the non-null values for you.
The result you got is a mysql_result object, which you need to use to get to the actual data of the query result.
The documentation of this object is here and I suggest that you read it thoroughly.
One possible way to do this is using this:
$resultArray = $result->fetch_row();
This will result in the first (and only) row of your query. It is represented as an array, with one value (since your query returns only one column). You can fetch that value like this:
return $resultArray[0];
You could also use any of the other fetch methods if you want your data in a different fashion.

Related

Array_Rand always returns same value PHP fetch array

I have this function:
function set_spell() {
global $connection;
$query = "SELECT * FROM Spells";
$result_set = mysqli_query($connection, $query);
$spell_id_list = mysqli_fetch_array($result_set);
return $spell_id_list;
Then I try to output a random ID from the array, but I always get ID 1.
$spell_id_list = set_spell();
echo $spell_id_list[array_rand($spell_id_list)];
When I run this query in MYSQL, I get a list of all ID's as expected. Why doesn't the code above select one at random?
This is probably a stupid questions that I'll smack myself after I see the answer... but I've been stuck for longer than I think I should be on it.
Thanks for the help.
You just returning only single result from your function so either create array of all fetched results & return the same, or simply use order by rand() in your query,
SELECT * FROM Spells ORDER BY RAND();

Performing a MYSQL query based off of $_GET results

When a user clicks an item on my items page, it takes them to blank page template using $_GET to pass the item brand and model through.
I'd like to perform another MYSQL query when that user clicks through to populate the blank page with the product details from my database. I'd like to retrieve the single row using the model number (unique ID) to populate the page with the information. I've tried a couple of things but am having a little difficulty.
On my blank item page, I have
$brand = $_GET['Brand'];
$modelnumber = $_GET['ModelNumber'];
$query = mysql_query("SELECT * FROM items WHERE `Model Number` = '$modelnumber'");
$results = mysql_fetch_row($query);
echo $results;
I think having ''s around Model Number is causing troubles, but without them, I get a Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given error.
My database columns looks like
Brand | Model Number | Price | Description | Image
A few other things I have tried include
$query = mysql_query("SELECT * FROM item WHERE Model Number = $_GET['ModelNumber']");
Which gave me a syntax error. I've also tried concatenating the $_GET which gives me a mysql_fetch_row() expects parameter 1 to be resource, boolean given error
Which leads me to believe that I'm also going about displaying the results incorrectly. I'm not sure if I need to put it in a where loop like I have with my previous page which displays all items in the database because this is just displaying one.
It seems that your "result" is pulling in too much information for a single variable.
Also, I don't think your table should have column names with spaces, I would suggest filling them all with dashes or underscores.
Here's my suggestion:
$qry = mysql_query("SELECT * FROM items WHERE Model_Number = '$modelnumber'"); //REMEMBER TO MAKE THE CHANGE "Model Number" -> "Model_Number"
while($row = mysql_fetch_array($qry)){
$brand = $row['Brand'];
$modelnumber = $row['Model_Number'];
$price = $row['Price'];
$description = $row['Description'];
$image = $row['Image'];
}
This will populate all of these variables with whatever you have in your tables.
First, notice the first comment on your question. You definitely want to add some sort of sanitation, mysql_real_escape_string at the very least, although PDO or Mysqli would be preferred.
Second, before getting a real answer to your question, let's get some more information about your error.
Try the following:
$brand = mysql_real_escape_string($_GET['Brand']);
$modelnumber = mysql_real_escape_string($_GET['ModelNumber']);
$query = mysql_query("SELECT * FROM items WHERE `Model Number` = '$modelnumber'")OR die(mysql_error());
$results = mysql_fetch_row($query);
var_dump($results);
mysql_error tell us what is going on behind the scenes.
If you are using mysql_fetch_row it will only returns a numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows http://php.net/mysql_fetch_row
If you need to retrieve the data inside that row. You need to use mysql_fetch_array()
also try using mysql_error();
$results = mysql_fetch_row($query) or die(mysql_error());
you will see the error output produce by your code

MySQL Query Enum

I have been working on this for a while now, I know it's simpler than what I am making it, but I just can't get it. I have some code where I am trying to query an enum either 1 or 0 from my table so this is exactly what I have to do this.
$username = 'test'
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='.$username.'");
Now I have all the connection stuff down I think, I get no errors there, but when I print this thing out in my echo I get this,
Heres my echo:
echo 'Hello, '.$username.', you Result is: '.$passResult.'!';
What I want to get is:
Hello, test, your Result is: 1
or
Hello, test, your Result is: 0
Now what I get is:
Hello, test, your Result is: Resource id #6
Now no matter what I do I get the same thing, I have no idea what I'm doing wrong here guys if someone could point this out that would be awesome. What this enum is being use essentially for a boolean just to see if the user has personally set a password not the computer generated version.
mysql_query returns a result resource, essentially a pointer to the memory where the results are buffered. That result set can contain many rows, as you can select many rows, so you need to fetch the row(s) you want then the column(s) you want from those rows.
/* execute the query and get a result resource back */
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='" . mysql_real_escape_string($username) . "'");
/* retrieve the first row from $passResult */
$row = mysql_fetch_assoc($passResult);
/* assign the usrSetPass column's value from that row to $passed */
$passed = $row['usrSetPass'];
Also, your query is wrong. You enclosed it in double quotes, so you're not actually breaking out of the string and concatenating $username when you use the single quotes and dots inside. I've corrected it above.
mysql_query doesn't return a value, it returns a resource (see here in the manual).
The returned result resource should be passed to another function for dealing with result tables (like mysql_fetch_array() or mysql_fetch_assoc()), to access the returned data.
Example based on your initial code:
$username = 'test';
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='".$username."'");
while ($row = mysql_fetch_assoc($passResult)) {
echo $row['usrSetPass'];
}

How do i parse the the value from a string in the function call?

i have function which is something like this
function multiple_delete($entity1,$entity2,$entity2) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $entity1;
echo $entity2;
echo $entity3;
}
and my function call is
multiple_delete('$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
keeping in mind the three value which i am passing through the parameter is the entity name of particular table.
now this function will print it as the string i.e ($row['pic_title'], $row['pic_brief']', $row['pic_detail']) and hence not parse it as the value which i want it to do. if it parse it as the value then i will be able to get the records from the database. i have tried with the combination of single quotes, doubles, with concatenation operator etc. is there any way i tell the script that do not parse it as the string instead treat it as it have been declared to fetch the value from database. does php have any function for this ? or i am going wrong with the logic.
if i skip the parameters and declare in the functions something like this.
echo $row['pic_title'];
echo $row['pic_brief'];
echo $row['pic_detail'];
it works perfectly fine . why is that when i try to achieve the same thing with the help of parameter it refuses to fetch the value from the database, and instead it returns the same declared string from the function call.
Please do not tell me that i dont need that parameter, i need it because i want it to perform the dynamic data manipulation, with regard to different tables and different table entities. and the above function is just the demonstration of my problem not the exact function. if you want to have a look at the exact function you can check here.
What is wrong with my function?
thank you
Just pass the names of the columns:
multiple_delete('pic_title', 'pic_brief', 'pic_detail');
Then you can use them to access the corresponding values in the row array by using the names them as keys:
function multiple_delete($entity1, $entity2, $entity3) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[$entity1];
echo $row[$entity2];
echo $row[$entity3];
}

PHP using count() with array

Im trying to get the amount of elements in an array using the count() function, the result is a bit puzzling to me, considere the following example.
Assume that the user ID provided is wrong, and therefore had no matches, wouldnt then the result of the count function be 0? yet it is 1. can you explain to me why?
thanks
$q = mysql_query("select password from users where user_name = '" . $userID . "'");
$check = mysql_fetch_array($q);
$result = count($check);
echo "RESULT:" . $result;
That's the wrong way to count rows in a result set. First of all, from the documentation on mysql_fetch_array()
Returns an array of strings that
corresponds to the fetched row, or
FALSE if there are no more rows.
Ergo, if we do this
echo count( false );
We can see the output is 1. Why? Because the count() documentation tells us that as well
If var is not an array or an object
with implemented Countable interface,
1 will be returned.
To do a proper count, use mysql_num_rows()
$q = mysql_query("select password from users where user_name = '" . $userID . "'");
$result = mysql_num_rows( $q );
if ( 0 == $result )
{
// no rows in result
}
use mysql_num_rows instead of count. count returns 1 for the value FALSE
count() returns 1 because in case of failure $check is not an array.
From the documentation:
If var is not an array or an object with implemented Countable interface, 1 will be returned
But you should anyway handle error cases directly (if the query fails your code shouldn't even get to the point where you analize its results). Also as other have correctly said, that's not how you count the number of results a query returns as that's what mysql_num_rows() is for
mysql_fetch_array returns false if there are no more rows. count(false) = 1.
Try using mysql_num_rows if you want to count the number of results.

Categories