-1

Hi I am trying to learn how to use PHP with MySQL but I can't get it to work. I can't run a simple SELECT query because I can't connect my database. Here is the code for how to tried to connect it.

//Creates connection

$conn = new mysqli($servername, $username, $password);

$link = mysql_connect($servername, $username, $password);

//Checks connection

if ($conn->connect_error) {
    die("Connection failed: ".$conn->connect_error);
}
mysql_select_db($db, $link); 

echo "Connection Successful<br>";

The $link and $conn variables are repetitive on purpose because I'm not sure which method to use.

luchaninov
  • 6,792
  • 6
  • 60
  • 75
  • `mysqli` and `mysql` are separate drivers. http://php.net/manual/en/mysqli.quickstart.connections.php Stick with the `mysqli` the `mysql_` is outdated. They are both used to connect to a mysql DB. – chris85 Jun 29 '15 at 00:58

1 Answers1

0

Use the following code:

<?php
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

    /* check connection */
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }

    if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
         printf("Select returned %d rows.\n", $result->num_rows);

        /* free result set */
        $result->close();
    }

    $mysqli->close();
?>
Arlind Hajredinaj
  • 8,380
  • 3
  • 30
  • 45
  • running this gives me an error: Warning: mysqli::mysqli(): (HY000/1044): Access denied for user ''@'localhost' to database 'david' in C:\xampp\htdocs\David\test.php on line 2 Connect failed: Access denied for user ''@'localhost' to database 'david' – David Dardik Jun 29 '15 at 01:21
  • what is your system setup, are you running xampp or you have mysql in a different server? find the IP of your mysql server and replace localhost with it – Arlind Hajredinaj Jun 29 '15 at 13:10