Hi All,
Can anyone please help me here?

I created one php file. My code is :

<?php

$conn  = mysql_connect("localhost","manish","manish","my_db");
if (empty($conn))
{
 die("mysql_connect failed ". mysql_connect_error());
}
print "connected to ". mysql_get_host_info($conn);

$result = $conn->query("SELECT id from test_manish",mysql_use_result);

while($row = $result->fetch_row())
{
  Print $row[0]. "<br\n>";
}
$result->free();


mysql_close($conn);

?>

I am receiving below error :

connected to localhost via TCP/IP
Fatal error: Call to a member function query() on a non-object in C:\webroot\database1.php on line 10

..

Please let me know what is wrong with this code?

    mysql_connect is procedural, not OOP so $conn is NOT an object but rather a resource.

    If you want to use the OOP approach you need to use mysqli firstly and secondly you need to instantiate it the OOP way.

    //psuedo code
    $conn = new mysqli("localhost","manish","manish","my_db");
    $res = $conn->query("SELECT 1 FROM test_manish");

    OR to continue using mysql (not recommended, you should use mysqli or PDO):

    $conn = mysql_connect("localhost","manish","manish","my_db");
    $res = mysql_query("SELECT 1 FROM test_manish",$conn);
    

      Hi Derokorian

      It worked .Thanks for ur quick reply.

      i used second option to connect to mysql.

        Hi Friend ,
        i need one more help here.

        i modified below code:

        <?php

        $conn = mysql_connect("localhost","manish","manish","my_db");
        if (!$conn)
        {
        die("mysql_connect failed ". mysql_error());
        }
        print "connected to ". mysql_get_host_info($conn). "<br />";

        $qry = "SELECT id from test_manish where id = 1";

        $result = mysql_query($qry,$conn);

        if (!$result)
        {
        echo "could not run :" . mysql_error();
        exit;
        }

        $row = mysql_fetch_row($result);

        mysql_close($conn);

        ?>

        when i run this it gives me below error message :

        connected to localhost via TCP/IP
        could not run :No database selected

        can u please help me?

        //Manish n

          Look at the page for mysql_connect again, the 4th param is a bool representing if its a new link or not. You need to use mysql_select_db to select the db to use.

          $conn = mysql_connect("localhost","manish","manish");
          if (!$conn)
          {
          die("mysql_connect failed ". mysql_error());
          }
          print "connected to ". mysql_get_host_info($conn). "<br />";
          
          // Select database
          mysql_select_db("my_db",$conn);
          
          $qry = "SELECT id from test_manish where id = 1";

            actully the problem was, user manish did not have access to table test_manish.

            so i grant access to table. and hence the problem resolved.

              Write a Reply...