-1

I'm new in PHP and follow this tutorial connect php webservices to android below is my code i change MySQL to MySQLi everywhere but still its show error:

enter image description here

    <?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password=""; //replace with database password 
$db_name="emp_info"; //replace with database name

$con=mysqli_connect("$host", "$username", "$password")or die("cannot  
  connect"); 
mysqli_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info"; 
$result = mysqli_query($sql);
$json = array();

if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysqli_close($con);
echo json_encode($json); 
 ?> 
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • `mysqli_select_db` that takes 2 parameters. Please read the manual. Now, using http://php.net/manual/en/mysqli.error.php would have told you about it. – Funk Forty Niner Mar 28 '16 at 15:30
  • There is literally no point to write `"$username"` in your code when `$username` will do. It would be in your best interest to shed these awful habits. – tadman Mar 28 '16 at 15:31
  • i just simple copy paste the tutorial code http://codeoncloud.blogspot.com/2013/07/android-mysql-php-json-tutorial.html – syed ahmed Mar 28 '16 at 15:33
  • 3
    the tutorial's pretty crappy. you'll find that probably 95%+ of php tutorials on the web are outdated, badly written, full of security vulnerabilities, or just plain wrong. there's a LOT of crap out there. – Marc B Mar 28 '16 at 15:34
  • 1
    Oh, and this `$result = mysqli_query($sql);` is also failing you. RTFM http://php.net/manual/en/mysqli.query.php as a wise man once said ;-) – Funk Forty Niner Mar 28 '16 at 15:35
  • Couldn't agree with you more there Marc - @MarcB – Funk Forty Niner Mar 28 '16 at 15:35

1 Answers1

1

There are two solution, first use the 4th argument in mysqli_connect().

Like this:

$con=mysqli_connect($host, $username, $password, $db_name)

Second, you need pass the connection in mysqli_select_db()

$con=mysqli_connect($host, $username, $password);
mysqli_select_db($con, $db_name);

Almost all function in MySQLi needed the conection at first argument, so mysqli_query() need the connection too.

$con=mysqli_connect($host, $username, $password, $db_name)or die("cannot connect"); 

$sql = "select * from emp_info"; 
$result = mysqli_query($con, $sql); //<--- here query need the connection
rray
  • 2,518
  • 1
  • 28
  • 38