views:

189

answers:

4

Here is my problem, i have a class with a ave method, i want to pass a Mysql DB link to it, so i create a new object from the class, and call the saveProperty method, and in my main file i created a MySQL connection and saved the link in a var called $db so when i call the method it's link this: saveProperty($db).

but insted of saving the data i get an error:

Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\aqaria\classes\property.php on line 75

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\aqaria\classes\property.php on line 99

which means that i didn't pass the link right? but how?

here is some of my code:

<?php

  class test 
  {




    function saveProperty($db)
    {

     $sql = "<<query goes here>>" 

     mysql_query($sql,$db);

     if(mysql_affected_rows()>0)
     echo "<h3>Data was saved</h3>";
     else
     echo "<h3>Error saving data</h3>";

    }


  }

here is the calling code:

$db = mysql_connect('localhost','root',''); 
mysql_select_db("aqaria",$db); 
$property = new Property(); 
$property->saveProperty($db);

although it would work if i added the gloabl keyword to method of the class i was wondering if i can PASS the link to the database connection?

A: 

You don't have the database object in your function.

Add this at the top:

global $db;

Edit: to pass it into your function you'd do this:

$db = mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db("aqaria", $db) or die(mysql_error());

agar_add_offer($someDataFromSomewhere, $db);

function aqar_add_offer($data, $db)
{
    $property = new Property();

    //do some data manipulation

    $property->saveProperty($db);
}
Greg
ok it worked thanx, i'm new to OOP in php so care to give me a simple explanation?
Thamood
but this is only accessing the global $db var, how can i pass a link to the method without using the global var?
Thamood
You'd pass it as an argument to the function
Greg
i tried that and it gave me the error above "supplied argument is not a valid MySQL-Link resource"
Thamood
A: 

It is without doubt possible to pass db_links around in methods.

Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\aqaria\classes\property.php on line 75

Check you database credentials and output with mysql_error()

Stojg
A: 

Have you tried with a reference?

Also you might want to use $db in mysql_affected_rows()

function saveProperty(&$db)
{

    $sql = "<<query goes here>>" 

    mysql_query($sql,$db);

    if(mysql_affected_rows($db)>0)
    echo "<h3>Data was saved</h3>";
    else
    echo "<h3>Error saving data</h3>";

}
Jake
Thamood
A: 

I just use global $db in each method of class I need to use mysql. $db is defined outside of class.

Is there a method I do not have to use 'global $db' also in each method.

Satya Prakash