-2

I had a website built in PHP a good few years back and my provider has now upgraded to PHP 7.

I'm not getting the error Fatal error: Uncaught Error: Call to undefined function mysql_connect(). I have some HTML knowledge but no PHP. From researching I can see that mysql_* functions have been removed from PHP 7.

Can anyone help with the code so I can get it working again?

<?php
$username="cwuser";
$password="XXXXX";
$database="cwdb";

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM car ORDER BY j_price DESC";
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();
?>
  • 1
    Is mysql installed? – Ingus Dec 17 '18 at 10:45
  • 1
    You'll need quotes around "localhost" `mysql_connect('localhost',$username,$password)`; – Panda Dec 17 '18 at 10:45
  • 1
    Are you using PHP > 7.0 because the `mysql_` API has been removed from that and ALL future versions – RiggsFolly Dec 17 '18 at 10:47
  • Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in new code **[this happens](https://media.giphy.com/media/kg9t6wEQKV7u8/giphy.gif)** it is deprecated and has been for years and is gone for ever in PHP7.0+. If you are just learning PHP, spend your energies learning the `PDO` or `mysqli` database extensions and prepared statements. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly Dec 17 '18 at 10:47
  • See also https://stackoverflow.com/questions/1390607/how-to-change-mysql-to-mysqli, or alternatively you could look at `PDO` instead – ADyson Dec 17 '18 at 11:16

1 Answers1

0

You need to use mysqli_* functions instead of mysql_*

<?php
       $username="cwuser";
       $password="XXXXX";
       $database="cwdb";

       mysqli_connect(localhost,$username,$password);
       @mysqli_select_db($database) or die( "Unable to select database");
       $query="SELECT * FROM car ORDER BY j_price DESC";
       $result=mysqli_query($query);

       $num=mysqli_numrows($result);

       mysqli_close();
    ?>
Gautam Rai
  • 2,445
  • 2
  • 21
  • 31
  • Thanks for the reply, I'm still getting the error below Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /customers/d/3/3/XXX.co.uk/httpd.www/stock_list.php:6 Stack trace: #0 {main} thrown in /customers/d/3/3/XXX.co.uk/httpd.www/stock_list.php on line 6 – user2037003 Dec 17 '18 at 19:07
  • It seems you are still using mysql_connect() function, you should use mysqli_connect(), see my answer – Gautam Rai Dec 18 '18 at 06:35