mySQL statement not running in PHP variable declaration - php

In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.

When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;

use this:
$amount = "SELECT MAX(id) FROM table";

You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);

You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);

I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!

Related

Display amount of registered users in MySQL database using PHP

I want to display the current amount of users registered in my database (it's called dalton) / the users are stored in a table in that database called simpleauth_players. It stores their name, hash, registerdate, logindate, and lastip.
I want to somehow use a PHP code that (logs me into the database) and displays the current amount of names in the database. So I can display a message like "Hey, there is currently 1,894 registered players!" inside of my HTML/PHP page. I'm kinda a novice it would be awesome if somebody could share the code and instructions.
My code:
$connection = mysql_connect('host', 'username', 'password');
mysql_select_db('database');
$query = "SELECT * FROM simpleauth_players";
$result = mysql_query($query);
$registered = "SELECT COUNT(*) FROM dalton.tables WHERE simpleauth_players = 'name' and TABLE_TYPE='BASE TABLE';
echo "$registered";
mysql_close();
This is the code I used to display the amount of registered players (AKA rows) in the simpleauth_players table.
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("dalton", $link);
if ($_GET['task'] == 'total') {
$get_db = 'simpleauth_players';
$result = mysql_query("SELECT * FROM $get_db", $link);
echo '{"task":"total","amount":"';
echo mysql_num_rows($result);
echo '"}';
}
?>
select count(*) as total_player from simpleauth_players
OR
$sql = "select * from simpleauth_players";
$result = mysqli_query($con,$sql);
$count = mysqli_num_rows();
echo "Total ".$count." Players";
Try this one assumed that your column name is language
SELECT COUNT(*) FROM simpleauth_players WHERE language = "PHP"
or if you want to get count by each language type you can use this
SELECT COUNT(DISTINCT user_id) AS Count,language FROM simpleauth_players GROUP BY language
As per your original post/question Since you have not provided us with the MySQL API you're using to connect with, here's an mysqli_ version, using MySQL's aggregate COUNT() function, which will count the number of given rows in a table:
$connection = mysqli_connect('host', 'username', 'password', 'database');
$result = mysqli_query($connection, "SELECT COUNT(*) as count
FROM simpleauth_players"
);
while ($row = mysqli_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}
Edit: if using mysql_
$connection = mysql_connect('host', 'username', 'password');
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('database', $connection);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
$result = mysql_query("SELECT COUNT(*) as count
FROM simpleauth_players", $connection);
while ($row = mysql_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}

php visitor counter not working

I am having a problem with mysql. My php code is not working.
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
}
?>
I have tested putting some echo on my codes. Once i put the echo code on the while loop the echo doesnt work. Can anyone help me.
Try this :
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
$current_count = 0;
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
}
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
Check if your SELECT query works by change the code:
mysql_query("SELECT * FROM user_count") or die(mysql_error());
Check if there is data in de table user_count and edit the query:
while($row = mysql_fetch_assoc($find_counts))
{
print_r($row); //to print the database row
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts=".$new_count); // no need to specify the database, you already did with mysql_select_db.
}
Dont need to specify DB, and quotes are wrong, change to:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count");
You also might want to specify a page:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count WHERE page = '$this_page'");
what are you trying here ?
mysql_query("UPDATE 'visitor_counter' . 'user_count' SET 'counts'=$new_count");
whats the table name ?
i guess your tablename is user_count
or do you have more than one tablename you like to update ?!?!?
if tablenam eis user_count it should look like
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
so the total while would be
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
}
Important
Dont use
'tablename'
in your sql query... if you like to declair a tablename use
`tablename`
Use single query:
UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1;
then do your SELECT ... FROM
because passing variable into sql query for this kind of operations are not always safe
and here is Your code:
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
mysql_query("UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1");
$counts = array();
$result = mysql_query("SELECT * FROM user_count");
while($data = mysql_fetch_assoc($result)) {
$counts[$data['id']] = $data['counts'];
}
?>
I'm really surprised to see everybody here posts code using the old and deprecated mysql functions (although some of them stated this is wrong). I would like to advice you AGAINST using mysql functions - they are deprecated as of version 5.5. You should use either mysqli or PDO instead. In my opinion, you should be using PDO as it provides support for almost all databases and you could use prepared statements.
Now to your code - I'm not quite sure why would use a cycle to count all of the records in the counts column. A much better way to do this is by using atomic increment - it will also guarantee your counter is properly incremented in case two queries are trying to increment the value simultaneously. Although you haven't posted your table structure, I believe something like this should do the work:
<?php
// Database connection settings
$db_host = '127.0.0.1';
$db_name = 'visitor_counter';
$db_user = 'root';
$db_pass = 'root';
// Try to connect to the database
try {
$dsn = 'mysql:host='.$db_host.';dbname='.$db_name;
$db = new PDO($dsn, $db_user, $db_pass);
} catch ( PDOException $e ){
// Do something if connection could not be established
throw new ErrorException("Could not connect to database!",0,1,__FILE__,__LINE__,$e);
}
// Find counts
// Assuming you have a user_id column in your `user_count` table.
$user_id = 1;
// Update counter
$update = $db->prepare('UPDATE user_count SET counter=(counter+1) WHERE user_id = :user_id');
$update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$update->execute();
?>
P.S. In this code I'm assuming you're saving the visitor counter in the user_count.counter column and whenever somebody visits that user, the counter column is incremented for that specific user, rather than updating the counter for all users (as your code suggests).

Count number of rows in SQL database

I am trying to view how many rows there are based on a SQL query using PHP.
I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query.
<?php
$host = 'localhost';
$user = 'MyUsername';
$pass = 'MyPassword';
$database = 'MyDatabase';
$con=mysqli_connect($host,$user,$pass ,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
mysqli_close($con);
?>
All it returns is the text Rows on the screen, without the number of rows at the start.
Like I said, this same query works and returns a value if I try and select a row using:
while($row = mysqli_fetch_array($result))
{
echo $row["test"];
}
Anyone know why it won't return the number of rows?
You are using MySQLi. Because of you don't have a mysql query, mysql_num_rows doesn't return desired value.
You have to replace your mysql function with mysqli equal:
$num_rows = mysqli_num_rows($result);
You are using Mysqli to you should use mysqli_num_rows
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysqli_num_rows($result);
If you want only count then you can directly use count(*) like this:-
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result;
I'll do some thing like this:
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result

PHP, resource id# instead of actual string

I have run across a problem during my query service to add a row in an online database in PHP. The addition of the row works just fine. I get user id and book id from the url and fetch the names of the book and the user to put into the row which i add to my third and last table.
When I get the names, put them in an array, json encode it and then echo it, it works. But when I put them in the row it prints resource id#3 and resource id#4 instead of the names.
Any ideas?
Here is my service:
<?php
$con = mysql_connect("localhost","root","root");
$userid=$_GET['uid'];
$id = $_GET['bookid'];
$type = $_GET['type'];
$zero = '0';
$one = '1';
$date = date("Y-m-d");
$arr = array();
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "error connection";
}
mysql_select_db("Jineel_lib",$con) or die("Could not select database");
$bkName = mysql_query("SELECT Name from books where ID='".$id."'");
$userName = mysql_query("SELECT Name from people WHERE User_ID='".$userid."'");
while($obj = mysql_fetch_object($userName))
{
$arr[] = $obj;
}
echo json_encode($arr);
if($type == 'borrow')
{
$query="UPDATE books set Availablity = '".$zero."' where ID= '".$id."' ";
mysql_query($query) or die (" borrow operation failed due to query 1");
$query1="INSERT into borrowed (BookID, BookName, BorrowerID, BorrowedName, DateBorrowed, Extended, Returned) values('".$id."','".$bkName."','".$userid."','".$userName."','".$date."','".$zer‌​o."','".$zero."')";
mysql_query($query1) or die (" borrow operation failed to due query 2");
echo "borrow success";
}
else if($type=='return')
{
$query="UPDATE books set Availablity = '".$one."' where ID= '".$id."' ";
mysql_query($query) or die (" return operation failed");
$query1="UPDATE borrowed set Returned = '".$one."' where BookID= '".$id."' ";
mysql_query($query1) or die (" return operation failed 1");
echo "return success";
}
else
echo "invalid parameters";
?>
THANK YOU IN ADVANCE
You don't actually retrieve the userName value here:
$userName = mysql_query("SELECT Name...
$userName is just the result resource object returned from the query. You do use mysql_fetch_object later on, which is appropriate, but then you try to use the actual result resource in your insert query:
$query1="INSERT into borrowed ...
It gets converted to the string you see. Instead, you need to use $obj->Name (you fetch the result into $obj, and presumably there is only one result). If there is more than one possible result, you will have to do that in a loop.
Listen to all of the comments on your question.

returing one value from the database using php

How do I fetch only one value from a database using PHP?
I tried searching almost everywhere but don't seem to find solution for these
e.g., for what I am trying to do is
"SELECT name FROM TABLE
WHERE UNIQUE_ID=Some unique ID"
how about following php code:
$strSQL = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = mysql_query($strSQL) or die('SQL Error :: '.mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['name'];
I hope it give ur desired name.
Steps:
1.) Prepare SQL Statement.
2.) Query db and store the resultset in a variable
3.) fetch the first row of resultset in next variable
4.) print the desire column
Here's the basic idea from start to finish:
<?php
$db = mysql_connect("mysql.mysite.com", "username", "password");
mysql_select_db("database", $db);
$result = mysql_query("SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID");
$data = mysql_fetch_row($result);
echo $data["name"];
?>
You can fetch one value from the table using this query :
"SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID limit 1"
Notice the use of limit 1 in the query. I hope it helps!!
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();

Categories