MYSQL & PHP How to show how many results in a table - php

Im a noob and only 16, i have a table full of videos that can be added though the website.
How do i show the Number of videos in the my-sql database that i can just past in between some php tags?
the database has tables likes users etc but one is "post" and i need to show how many records there are in it.
there is a config.php file that connects to the database which is like this (with the real info)

<?php
$dbh = new PDO('mysql:dbname=mydbname', 'username', 'password');
echo $dbh->query('SELECT COUNT(*) FROM videos')->fetchColumn();
?>

Hi james this is the example code from php.net. Which echo the number of rows in table 1. You could try playing with it.
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
Hope you understand

If you know how to connect database to PHP, mysql_num_rows() might come in handy. Read the manual here.
Sample code:
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * FROM person";
$result = mysql_query($sql,$con);
echo mysql_num_rows($result);
mysql_close($con);
?>

Just use COUNT() in your SQL
$con=new mysqli('localhost?', 'username', 'password', 'tablename');
$stmt=$con->prepare('SELECT COUNT(*) FROM videos');
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
echo 'There are '.$result.' Videos in the DB.';

By learning on tutorials, doing some PHP/MySQL tests, reading some books and searching on Google keywords like "MySQL counting rows in table + PHP"...

Related

Trying to output the richest user in my database through php

I know this is a bit of a rookie question but I'm trying to output the richest user's name on my website.
So my table is called Users
I have Column 1 ('Name') containing the names of all the users, and Column 2 ('Bank') containing their account balance.
I would like to find the richest user and output them on my website.
This is what I've got so far.
while ($row2 = mysqli_fetch_array($sqldataGang, MYSQLI_ASSOC)) {
$sqlgetGang = 'select name from gangs where bank = (select max(bank) from gangs) order by bank;';
$sqldataGang = mysqli_query($dbcon, $sqlgetGang) or die('Connection could not be established');
$welthiestGang = $row2['name'];
}
I know that there is a connection to the database as I have other statistics from other tables working... I have no idea why this isn't working... Thanks for the help in advance :)
$sql = 'SELECT name FROM gangs ORDER BY bank DESC LIMIT 1';
That should do it.
You need to fetch a row from your $sqldataGang query object.
Add a line something like this to your program to fetch the result right after your call to mysqli_query()
$row2 = mysqli_fetch_array($sqldataGang, MYSQLI_ASSOC);
But, also, beware. A wise programmer always checks queries for errors. You can see how to do that in the examples here.
Use this query
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT name,bank FROM Users order by bank desc limit 1";
$result = mysqli_query($conn, $sql);
This will give you the richest person in your website

Display an int value from SQL database using PHP

I'm busy with a school project where I need to register users. I created the database and added the tables and can add users. What I just can't get right is to display the next available user id in the table.
I'm using php to retrieve the highest value but when I use echo the variable won't show. There is no error, there is no output at all, just the rest of the page.
Here is the code:
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM users" or
die(mysql_error());
$highest_id = mysqli_query($db, $query);
echo $highest_id;
?>
The code successfully connects to the database, the column is called userid, it contains int values and there are other columns as well.
All other code in the script runs perfectly, it's just this part that I can't get to work.
I have spent the last two days reading and searching for answers and I am at my wits end. Any help would be appreciated.
Thank you.
could be your table is User and not Userid
$query = "SELECT MAX(userid) AS userid FROM users"
Anyway for fetching you should use eg:
$result = mysqli_query($db, $query);
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo $row[0];
The mysqli_query returns a general object that contains the results array. You have to use the mysqli_fetch_row.
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM userid" or die(mysql_error());
$highest_id_query = mysqli_query($db, $query);
var_dump($highest_id_query); // so you could check the object attributes
//loop results from query
while($row=mysqli_fetch_row($highest_id_query)){
$highest_id = $row['userid'];
echo $highest_id;
}
?>
You could also use the sql statement: SELECT COUNT(*) FROM userid
Be sure to name your tables correctly! SELECT COUNT(*) FROM users

How to get last created ID

No matter what I try - I cant seem to pull the last created id of the query I inserted to mySql.
I read here about syntaxes that are deprecated and all sort of code that wont work.
I tried both functions (I use bigint) so I understand that this is how to go:
if (($result = $conn->query("SELECT LAST_INSERT_ID()")) === FALSE) {
die(mysql_error());
}
if ($result->fetch_assoc()) {
$id = $row[0];
echo $id;
}
but nothing!!
Can someone please just give me a full simple php code sample of how to do it?
You can use $result = $conn->insert_id; to know last inserted row
Try this to get the last insert Id,
echo mysql_insert_id();
Dont use mysql its depricated, instead use mysqli or PDO. To get last inserted record use mysqli_inserted_id(). The following shows the snipped how to use-
<?php
$link = mysqli_connect("localhost", "username", "password", "dbname") or die('Facing some problem connecting with database');
$query = "INSERT INTO `table_name` VALUES (v1, v2, v3...vn)";
mysqli_query($link, $query);
printf ("New Record with id %d inserted", mysqli_insert_id($link));

mysql Show tables returns all +1 with TABLES "number of rows" as first value

When i recently wanted to list all tables in a database in php i made the simple MySQL query:
$tables_query = mysql_query('show tables');
while ($test = mysql_fetch_array($tables_query)) {
echo "Table: {$test[0]}<br />";
}
The first result is
TABLES 105
address_book
I don't have a table called "TABLES 105" but the mysql_num_rows also shows, that there is 105 results, even that my database only contains 104 table
If i try to request "show tables" directly on the MySql server, it works fine and i get 104 rows as result. It also worked before and i can't seem to find anything about this, so im hoping someone can help me in here.
It also affect when i call directly to the mysql server. I got access with an other user login for an other database, on the same server and here is no issues at all.
Its questionable how that 105 got there in the first place, most likely this is caused by that mysql_num_rows function that you mentioned as fetch_array actually fetches the rows, but here's one on MySQLi, stop using MySQL anymore:
$db = 'test'; // database name
$con = mysqli_connect('localhost', 'username', 'password', $db);
$tables_query = mysqli_query($con, "SHOW TABLES FROM {$db}");
while($table = mysqli_fetch_assoc($tables_query)) {
echo $table["Tables_in_{$db}"], '<br/>';
}
An alternative way of course is to delve into information_schema:
$db = 'test'; // database name
$con = mysqli_connect('localhost', 'root', '', $db);
$tables_query = mysqli_query($con, "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{$db}'");
while($table = mysqli_fetch_array($tables_query)) {
echo $table['TABLE_NAME'], '<br/>';
}

Get a row from a database based on querystring

BIt of a php/mysql noob here, hope someone can help.
Ok so i have a URL which has an id in the querystring like so: wwww.mysite.com/page1.php?id=1
What i want to do is connect to a table in the database and get the data from the columns on one row where the first column named ID equals the id number held in the querystring.
I then want to print the data from each column in different div's elsewhere on the page.
There's also the additional issue of what to do if there's no row in the table with the same id as the querystring, i'd want it to change the id in the querystring to 1 and load that rows data.
I had a little go, i know it connects ok but i have no idea if the rest is what i want:
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=".$_GET['ID']."";
echo $result['A'];
mysql_close($link);
?>
And then put this in the div's to print the data.
<?php echo $result['A']; ?>
Am i along the right lines or completely wrong?
$dbConnection = mysql_connect('Address', 'Database', 'Password');
if (!$dbConnection) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = $dbConnection->prepare("select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per = ?");
$query->bind_param('s', $per);
$query->execute();
$result = $query->get_result();
<?php echo $result; ?>
use this code first to avoid SQL Injection second that's the way it should work in PHP first prepare the query second execute and only then show it.
Use mysql_query function in your code.
mysql_* functions is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=$per";
$result = mysql_query($query, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['A'];
mysql_close($link);
?>

Categories