Simko Simko - 4 months ago 8
PHP Question

get value of mysql db by random

I want a code to get database row
I have table->(site) and two Columns->(url,rank)

rank should more than 0

I run this code :

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$conn = new mysqli($servername, $username, $password, $dbname);
$queryt = "SELECT url FROM site WHERE rank>0 ORDER By RAND() LIMIT 1";
$resultt = mysql_query($queryt) or die(mysql_error());
while($row = mysql_fetch_assoc($resultt)) {
echo $row['url'];
}


but say (database not selected)

Answer

Try using mysqli connection like so

$con=mysqli_connect("localhost","my_user","my_password","my_db");
mysqli_select_db($con,"test"); // not compulsory

Or try telling mysqli to throw exceptions

mysqli_report(MYSQLI_REPORT_STRICT);
try {
         $connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
    } catch (Exception $e ) {
         echo "Service unavailable";
         echo "message: " . $e->message;   // not in live code obviously...
         exit;

Also you are using mysqli to connect and mysql to query database, there is a difference among both

Hope it helps !

Comments