Salik
Salik

Reputation: 518

Cannot connect to MySQL using MySQLi_connect

I am trying to fetch results using ajax,php and MySql. However I am getting following errors on my server side script.

Warning: mysqli_select_db() expects parameter 1 to be mysqli, resource given in D:\htdocs\classes\xxx on line 10

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource

The server side code is as follows:

<?php
$q = intval($_GET['q']);

$con= mysqli_connect("localhost","root","abcd123") or die ("could not connect to mysql"); 

mysqli_select_db($con,"payrolldb001") or die ("no database"); 

$sql="SELECT substationid,substationcode FROM wms_substation WHERE assemblylineid = '".$q."'";

$result = mysqli_query($con,$sql);


echo "<select>";
while($row = mysqli_fetch_array($result))
  {
  echo "here";
  echo "<option>". $row['substationcode'] . "</option>";
  }
echo "</select>";

mysqli_close($con);
?>

I can not figure out where am i going wrong.Please help.

Upvotes: 0

Views: 24565

Answers (2)

Abhijit
Abhijit

Reputation: 941

    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    //Open a new connection to the MySQL server
    $mysqli = new mysqli('localhost','dbu','password','dbname');

    //Output any connection error
    if ($mysqli->connect_error) {
        die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
    }

    //MySqli Select Query
    $results = $mysqli->query("SELECT * FROM users");

    while($row = $results->fetch_assoc()) {
        echo $row["id"];
    }  


    // Frees the memory associated with a result
    $results->free();

    // close connection 
    $mysqli->close();

Upvotes: 3

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$con = mysqli_connect("localhost","root","abcd123","payrolldb001") or die("Error " . mysqli_error($con));
$sql="SELECT substationid,substationcode FROM wms_substation WHERE assemblylineid = '".$q."'";

$result = mysqli_query($con,$sql);
...

Or

$con= mysqli_connect("localhost","root","abcd123") or die ("could not connect to mysql"); 

mysqli_select_db($con,"payrolldb001") or die ("no database"); 

Read mysqli_select_db

Upvotes: 4

Related Questions