MySQL Count does not fill variable - php

Problem is:
I want to count the number in my column r_start where the r_start dates are between my other two variables. But it always gives me the Error Notice: Undefined variable: z in [path] on line 173. So it doesn't fill the variable, what makes me think that the COUNT does not work porperly. I did a lot of reasearch and tried some things, but I simply don't find the cause..
$sqld = "SELECT r_start, COUNT (*) FROM reservation WHERE r_start BETWEEN '".$cid."' and '".$cod."' GROUP BY r_start";
if ($result = $con->query($sqld)) {
$z = mysqli_fetch_assoc($result);
}
This error only appears with the COUNT tag. In my other queries it works absolutly fine.
f.e.:
$sqlc = "SELECT * FROM reservation where r_ende between '".$cid."' and '".$cod."'";
if ($result = $con->query($sqlc)) {
$y = mysqli_fetch_assoc($result);
}
Can anybody tell my why? Have I done something wrong?

MySQL generally does not recognize a space between a function and the opening paren. I would also advise that you give the column an alias:
SELECT r_start, COUNT(*) as cnt
FROM reservation r
WHERE r_start BETWEEN '".$cid."' and '".$cod."'
GROUP BY r_start;
You should also learn to use parameters to pass values into queries. Not using parameters makes the code subject to unexpected (and hard-to-debug) syntax errors, as well as making it vulnerable to SQL injection.

Related

Double mysql_fetch_array (get information from the other table to get data) / nest

I tried searching for this question, but theirs is a different error. I'm using PHP 5.2 for some reason.
What I'm trying to do is, get the mysql_fetch_array from one table, then use a column of that table to get a row from another table.
Here is my code (Advanced apologies for the horrible format)
$sql = mysql_query("SELECT * FROM testimonies WHERE visibility != 'Hide' ORDER BY date_submitted DESC");
$testimonyCount = mysql_num_rows($sql); // count the output amount
if ($testimonyCount > 0) {
//get data 'testimonies' table
while($info = mysql_fetch_array($sql)){
$username = $info['username'];
//Get id (in admin table) where username = username (in testimonies table)
$userid = mysql_query("SELECT * FROM admin WHERE username = $username LIMIT 1");
while($user = mysql_fetch_array($userid)){ $id = $user['id'];}
$testimonies .= "<div class='row'><div class='col-lg-2'><center>
<img src='Pictures/Profile_Pictures/".$userid['id'].".jpg' width='160' height='160'>
<br>".$info['username']."</center></div><div class='col-lg-2'><center>
<img src='back/inventory_images/34.jpg' width='160' height='160'><br>"
.$info['product_used']."</center></div><div class='col-lg-8'><center><u>(Date: "
.$info['date_submitted']." - Ordered from our branch in <strong>"
.$info['branch_ordered']."</strong>, City)</u></center>".$info['testimony']."
</div></div><br>";
}
}
else {
$testimonies = "No one has submitted their testimonies yet.";
}
So you see, my table "testimonies" have a column of 'username' and so is the "admin" table.
What' I'm trying to do is get the row of the username (in admin table) where the username is the
same as the one in the "testimonies" table. I used the information from the 2nd table in line 14 for the image src.
Unfortunately it gives me this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/_____/public_html/Testimonies.php on line xx
Notice: Undefined variable: id in /home/_____/public_html/Testimonies.php on line xx
Other's from what I've searched get their data on the first loop, but I don't get anything at all. The 2nd loop is certainly a problem. Help.
Thanks.
First I'll mention that it's a really bad idea to build queries in a such a way that they can be looped. As is for each of your testimonies you're executing another query to get the admin info. So for 10 testimonies you're hitting MySQL 10 times [ +1 for the original query ]. You generally want to get in, get your data, and get out.
So the better way to handle this is to let MySQL do it for you, with a join :
SELECT *
FROM testimonies inner join admin on testimonies.username = admin.username
WHERE visibility != 'Hide'
ORDER BY date_submitted DESC
The above will only return you testimonies with a matching admin. If you wanted to return testimonies even if they don't have an admin you'd want an outer join. You'd replace inner join admin with left outer join admin
So remove your second while loop and try that.
Also, the mysql_ functions are deprecated .. so you shouldn't be developing new code using them. Try and get my change to work as-is but you should consider looking at PDO [ Why shouldn't I use mysql_* functions in PHP? ].

Mysql - SELECT columns from 2 tables using INNER JOIN error

This should be a basic question, but I haven't used Mysql for a very long time and forgot all the basic stuff. So SO programmers please bear with me.
I have 2 tables like this:
Table 1 (events): here
Table 2 (users): here
I would like to select all rows in the events table where event_invitees contains a username. I was able to do this using:
SELECT * FROM meetmeup_events WHERE event_invitees LIKE '%$username%'
Now I'd like to also select the event_invitees's photo from the users table (column called user_userphoto). My attempt to this was this:
$result = mysql_query("SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
WHERE event_invitees LIKE '%$username%'
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
This gave me an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource
How can I do this? What am I missing? Can you give me some examples?
Thanks in advance! I'll be sure to accept the working answer!
You should change your mysql functions to either mysqli / PDO, although the problem seems to be the query itsef. Should be:
SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter
WHERE event_invitees LIKE '%$username%'
(the WHERE clause at the end)
Sql fiddle demo: http://sqlfiddle.com/#!2/852a2/1
Its just a matter of getting the query coded in the correct order, and you might like to make it a little more managable by using alias's for the table names
Try this :-
SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'
This of course assumes that all the column names are correct and the mu.user_username = me.event_inviter does in fact make sence because those fields are in fact equal
Additional Suggestion
You are not actually issuing the query for execution by mysql.
You have to do this :-
$sql = "SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'";
$result = mysql_query($sql);
$rows = array('mysql_count' => mysql_num_rows($result) );
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
Now in your browser using the javascript debugger look at the data that is returned. There should at least be a mysql_count field in it even if there is no 'meetmeup_user' array, and if it is zero you know it found nothing using your criteria.

Why can't I use COUNT (*) now?

I want to count everything in a Table to make Sites, I'm using this exact code a few times in my php file but now all the sudden is simply doesnt work anymore.. I'm driving crazy
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM '$tablename'");
$anzahl = $stmt->fetch_array();
$eintraege = $anzahl["Anzahl"];
$stmt->close();
$max_eintraege = 2;
if($eintraege <=2){
$seiten = 1;
}else{
$seiten = $eintraege / $max_eintraege;
$seiten +=1;
}
$start = $_GET["site"] * $max_eintraege - $max_eintraege;
if(!isset($_GET["site"])){
$start = 0;
}
All I get is:
Fatal error: Call to a member function fetch_array() on a non-object in /home/u144584875/public_html/index.php on line 2377
I just can't find out whats the problem, it works like 5 times in my Script but not now.
Everything is Set and right, whats the problem?
You should add some error handling, but the problem is this:
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM '$tablename'");
You are quoting your table name, it should be:
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM $tablename");
or
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM `$tablename`");
in case the table name is a reserved word in mysql, starts with a number, etc.
Edit: If you add this before you open your database connection (or anywhere above your current code...), mysqli will throw errors and tell you exactly what is wrong:
mysqli_report(MYSQLI_REPORT_STRICT);
// ...
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM `$tablename`");
// ...
Your SQL syntax is wrong. Table names should not be wrapped in single-quotes ('). Use backticks to escape them instead.
Update your SQL query as follows:
SELECT COUNT (*) AS Anzahl FROM `$tablename`
The documentation of mysqli::query says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.
Obviously, you have an error, and it returns FALSE. Use mysqli::$error to find out what it is.

How can I find the number of rows in a table using SQL?

I need to know the total row count of a table to build my page forward/backward system on my site which lists federal bills. Here is my SQL query.
$query="SELECT COUNT (*) FROM bills";
$result = mysqli_query(dbcxn('bill'),$query);
$billcount = mysqli_fetch_assoc($result);
echo $billcount;
dbcxn() is a function I wrote, and I've used it on all of my SQL queries, so I am quite certain that it is not a source of error.
The error displayed on page is the following:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /opt/lampp/htdocs/unipartisan/includes/billvote.inc on line 76
I referenced a book on SQL to decide to use SELECT COUNT, but it seems to work differently than I have expected.
Change to,
$query = "SELECT COUNT(*) FROM bills"; // No space between COUNT & (*)
Always have practice of printing error if any.
if (!mysqli_query(dbcxn('bill'),$query)) {
printf("Errormessage: %s\n", mysqli_error(dbcxn('bill')));
}
As per #Dave's comment more detail on error can be found here.
I think you can try to give your count an alias and remove the space after COUNT
$query="SELECT COUNT(*) as total FROM bills";
Now you can print it with scope
echo $billcount['total'];
<?php
$query = "SELECT * FROM YOURTABLE";
$result = mysql_query($query,$yoursqlconnection) or die('query error');
$row = mysql_num_rows($result);
echo $row;
?>
Hop this help

Adding up values inside of a while loop

With the first query in the following code I am looking for the checkings made in Berlin under the game number two.
With the second query I want to give points for each of the checkings.
As you will see I am using the function SUM. But let's say that I have 2 checkings and the points for each checking are 50. Well, instead of echoing 100, with this code I echo 5050
What is wrong with it?
Thanks a lot
THE CODE IS CORRECTED AND WORKING, JUST IN CASE SOMEBODY NEEDS IT. Thanks to all
$querya = "SELECT * FROM checkins where gamesid=2 and city='Berlin'";
$resulta = mysql_query($querya) or die(mysql_error());
$sumOfPoints = 0;
while($rowa = mysql_fetch_array($resulta)){
$n = $rowa['venuesid'];
$queryb = "SELECT venuesid, SUM(points) as sumpoints from venues where venuesid='".$n."' GROUP BY venuesid ORDER BY venuesid";
$resultb = mysql_query($queryb) or die(mysql_error());
while($rowb = mysql_fetch_array($resultb)){
$sumOfPoints += $rowb['sumpoints'];
}
}
echo "Total points is $sumOfPoints<br/>";
Some suggestions
Use SUM(points) AS sum (only for clarity when use the sum)
Check that points are numerical fields not varchar.
points must be a string, you need to cast it
SUM(cast(points) as int)
and then follow Gaurav's point about labeling the compute
You're getting 5050 because your script is echoing 50 in two iterations of the loop.
From the looks of it, your second query's GROUP BY clause is not grouping on venuesid when it should be. So, first try changing your GROUP BY clause to:
GROUP BY venuesid
If that doesn't give you the result you're looking for, then you should try running your query directly against the database with a static value for venuesid to see what you get back from it, then perhaps update your question and we can take it from there.

Categories