Search code examples
phpmysqlsqllocalhostmysql-connect

can't seem to connect to msql, local host?


i can't seem to run this code under local host, my goal is to make a table that is supposed to show in a website but when i try to connect i get the error:

Warning: mysql_connect(): in C:\xampp\htdocs\PhpProject2\hent.php on line 5 can not connect

my site name: http://localhost/PhpProject2/hent.php

the code:

<html>
<body>
<?php 

mysql_connect('<server is here>','<my username here>','<password here>') 
or die('can not connect' );
mysql_select_db('<my username here>') or die ('can not connect to <username here>');  

$sql = "Select * from Customer";
$result = mysql_query($sql);
$number= mysql_num_rows($result);

for($i=0; $i < $number; $i++)
{
    $table = mysql_fetch_row($result);
    echo  $table[0], $table[1];
    echo '<br>';
}
?>
    </body>
</html> 

i'm using xampp and MySQL is running on port 3306:]

instead of my < username here >, < server is here >, < password here > there is real code :]

i would Appreciate any answer :]


Solution

  • Try this:

    <?php
      $host = "hostname";
      $user = "username";
      $password = "password";
      $database = "database";
    
      $link = mysqli_connect($host, $user, $password, $database);
      If (!$link){
          echo ("Unable to connect to database!");
      }
      else {
      $query = "SELECT * FROM Customer";    
      $result = mysqli_query($link,$query);
    
      while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
       echo  $row['<insert column name>']. "<br>";
      }
    }
    mysqli_close($link);
    ?>
    

    I have used the MYSQL library in this code. You should check if you column in mysql is called 0 and 1. B.T.W. I am using WHILE instead of FOR loop that is just a personal preference.