I've made a form that allows users to submit their name, a comment and a score from 1-6, which then is saved in a table in their respective fields; name, comment and score. I wan't to display the average score.
This is what I've found out so far:
$result = mysql_query("SELECT AVG(fieldName) FROM tableName");
How do I echo this out?
Give your result an alias, It makes accessing it easier.
Use mysql_fetch_assoc() to get your results
$result = mysql_query("SELECT AVG(fieldName) AS avg FROM tableName");
$row = mysql_fetch_assoc($result);
echo $row['avg'];
FYI, mysql_* is obsolete. Try PDO or mysqli instead.
Related
Spent the last few days researching this, but I think I'm just not getting it... I can usually do what I need to with PHP but am new to MySQL
I set up a MySQL database to hold some photos. The photo's are in separate galleries (gallery is denoted by a gallery field). The photo's are also indexed by an id number.
When displaying the photos (it all works perfectly up to now...), I would like to be able to jump to the next or previous photo in the gallery, but can't just us the next or previous id, as it could be from a different group (found that out the hard way ;)
from my research, I feel like I need to use this:
$sql = "SELECT id FROM gphoto WHERE gallery='$g' ORDER BY id DESC";
$query = mysqli_query($db_conx, $sql);
But $query doesn't seem to give me what I expect. It feels like $query it should contain an array if all id's which contain gphoto, and I should be able to just find my current id number, then jump one up or down, but when I try to read $query I get:
Cannot use object of type mysqli_result as array
I'm obviously misunderstanding something
Some people have suggested:
$result = mysqli_fetch_assoc($query);
I had tried this after reading the online manual extensively, but for some reason it only lists one item... in this case the last record.
If I run it as ASC, it lists the first. Should it be listing all records like I expect, or is it a different command?
C)
+1 for Fabio's response.
A good advice is to use PDO interface for accessing databases in PHP. It's a meaningful interface to construct, execute and fetch the results of your queries without the knowledge of the used db driver.
http://php.net/manual/en/book.pdo.php
You need to fetch data from database after executing your query to handle mysqli object you have just created
$query = mysqli_query($db_conx, $sql);
$result = mysqli_fetch_assoc($query);
Now you have the array you were looking for in your variable $result
if ($result = mysqli_query($db_conx, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
//mysqli_fetch_assoc fetches data by row
}
}
You are only getting 1 row, thats how mysqli_fetch_assoc works. If you want the entire result to be an array of the rows, use mysqli_fetch_all
I would recommend using PDO however like #ceadreak suggested.
I want to do something like this:
$query=mysql_query("SELECT userid FROM users WHERE username='$username'");
$the_user_id= .....
Because all I want is the user ID that corresponds to the username.
The usual way would be that:
$query=mysql_query("SELECT * FROM users WHERE username='$username'");
while ($row = mysql_fetch_assoc($query))
$the_user_id= $row['userid'];
But is there something more efficient that this?
Thanks a lot, regards
You've hit the nail right on the head: what you want to do is SELECT userid FROM users WHERE username='$username'. Try it - it'll work :)
SELECT * is almost always a bad idea; it's much better to specify the names of the columns you want MySQL to return. Of course, you'll stil need to use mysql_fetch_assoc or something similar to actually get the data into a PHP variable, but at least this saves MySQL the overhead of sending all these columns you won't be using anyway.
As an aside, you may want to use the newer mysqli library or PDO instead. These are also much more efficient than the old mysql library, which is being deprecated.
Not only can you, but you should. Unfortunately too many young developers get in the habit of selecting far too much data. Once you run your query, you don't need to do a while loop since you only have one record coming back. Instead, just use the following:
$sql = sprintf( "SELECT userid FROM users WHERE username = '%s'", $username );
$result = mysql_query( $sql ) or die( mysql_error() );
$data = mysql_result( $result, 0 );
if ( $data ) echo $data; // first userid returned
The second parameter of mysql_result() is the row index you would like to retrieve. 0 is first.
The "usual" way is to only select the columns that you need.
Any column that is part of the select and is not needed will slow down the retrieval. Partly because of network traffic and partly because the database engine can apply certain optimizations if only some columns are selected.
And select * is usually frowned upon in production code.
Your query is correct:
$query = mysql_query("SELECT userid FROM users WHERE username='$username'");
This will work if done correctly. Note that $username must be correctly escaped with mysql_real_escape_string. I'd recommend looking at parameterized queries to reduce the risk of introducing an SQL injection invulnerability.
One other thing you can change is to use mysql_result instead of your loop:
$the_user_id = mysql_result($result, 0);
This assumes that know you'll get only one row.
Yes, that's a great optimization practice!
Also, if you want to go a step further and make it super-optimized, try adding a LIMIT, like this: $query=mysql_query("SELECT userid FROM users WHERE username='$username' LIMIT 1");
This, of course, assumes you expect only one userid to be returned and will make the database engine stop once it finds it.
But, the most important thing: ALWAYS ESCAPE/SANITIZE YOUR INPUT DATA! (can't stress this well enough)
You can do this with a single line of code
echo array_values(mysqli_fetch_array($mysqli->query("SELECT name FROM user WHERE id='$userid'")))[0];
You must connect to the database as shown below before using this
$mysqli = new mysqli('HOST', 'USERNAME', 'PASSWORD', 'DATABASE');
Credits to #samuel t thomas
After I perform a database query, and some rows are echoed, it seems that I can't get the number of rows which are shown, after the query. Tried to use mysql_num_rows() but my $result is like this:
$result = $conn->query($sql) or die();
so I think that the problem is that I've used the built-in MySQLi() class, and for some reason
mysql_num_rows() is not working in accordance with this $result. How can I get it to work with the current $result I'm using, or is there any other way to return the number of rows using the MySQLi() class to create the $result??
mysql and mysqli are NOT interchangeable. They're two completely different modules, maintain their own separate connections, and are results/handles from one are NOT useable in the other. They may both use the same underlying mysql libraries and talk to the same database, but they're utterly independent of each other.
If you're using MySQLi, then stick with MySQLi functions, which for your problem would be to use http://php.net/manual/en/mysqli-stmt.num-rows.php
Note1: If you only need the number of rows in your table, it is better to do the folowing:
$result = $conn->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Note 2: Don't mix up mysqli_field_count and mysqli_stmt_num_rows. For example :
id firstname
1 foo
2 bar
3 baz
field_count is 2
num_rows is 3
OK, the title may be misleading, I'm a complete novice in MySQL queries via PHP
What im actually trying to do is display a specific title of a row in a link.. for instance:
<?php echo "Link Name"; ?>
url being the row which holds the name of the link eg, link-one. So the finished link would output (if you were to view source):
Link name
My question is how do i select a certain entry in the url row? not just the next/previous/random entry. This may be easy but i cant find an answer. Is this possible?
Will this do the trick?
SELECT url,fn FROM $dbtable WHERE url LIKE '%link-one' ORDER BY order ASC
For this you would do something like:
$sql = "SELECT * FROM table WHERE id='$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo ''.$row["name"].'';
Though php isn't as useful if you don't have a db back end I recommend reading through W3School's sql tutorials, they are quiet good (and free) http://www.w3schools.com/Sql/default.asp
I am wondering if there is a possibility.
I have a pagination script that grabs the content from a mysql database with php and using jquery to handle it all.
I want to add a filter to the pagination which will get rid of some content based on the users selection.
When the filter is set I would like the pagination numbers to update to compensate for the items that have been removed.
My biggest concern is that I'm getting the amount of pages to display directly from the database which would make it impossible to update the pagination numbers when filtered:
<?php
include('config.php');
$per_page = 3;
//Calculating no of pages
$sql = "select * from explore";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
Does anyone know if it is still possible to update these numbers when filtered.
Im mostly using this tutorial in case your wondering:
Here
Just to expand on what Byron said, here is how you do this (based on the code from your link):
Right now in the pagination.php there is a line that looks like this
$sql = "select * from messages";
and in pageination_data.php like this:
$sql = "select * from messages order by msg_id limit $start,$per_page";
Lets say you want a filter that only shows today's messages.
then you would need the following two lines:
$sql = "select * from messages where messages.date = curdate() ";
$sql = "select * from messages where messages.date = curdate() order by msg_id limit $start,$per_page";
of course I expect you will generate the sql statements dynamically in some way. What this allows is the sql server to do the filtering, all the application code stays as you have it.
Note: Remember if you are making dynamic sql to not leave yourself open to sql injection attacks. There are a number of other questions that address sql injection.
The solution is to do the filtration sever side. IE when you apply a filter you send the data to the server and the sql is updated to include/exclude whatever your filter says.