1

I m creating function that process query and pass it's return result back. so I used following code:

function test(){
     $query = "select * from mytable where id=123";
     $data = mysql_query($query) or die(mysql_error());

     return $data;
}

$info = test();

is it possible and can i use $info to get values as $info[0],$info[1]..

4 Answers 4

2

take a look at mysql_fetch_array function.

This function lets you iterate a query result which is a resource and turn each row into an array.Therefore you should use a while loop to get all rows in a resource;

Sign up to request clarification or add additional context in comments.

Comments

0

You're missing one vital part, returning the result of mysql_query() just returns a result pointer not the dataset. You should add mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_row:

function test(){
     $query = "select * from mytable where id=123 LIMIT 1";
     $data = mysql_query($query) or die(mysql_error());
     $result = mysql_fetch_row($data);

     return $result;
}

$info = test();

now you can use $info[0], $info[1]. When using mysql_fetch_assoc you could use $info['fieldname'].

I also added LIMIT 1, since you're sending a long an ID, this probably is unique and after 1 result there is most likely nothing else to be returned.

Comments

0

You can do that, however it is better in my experience to keep the database stuff encapsulated, so you don't expose MySQL resources outside of the database context that then further need mysql_fetch_assoc() and the like on them.

I would use PDO there, and return the results of fetchAll(PDO::FETCH_ASSOC). That way, $info has the data it needs without needing to run further database functions on.

Comments

0
<?php

    $link = mysql_connect('localhost', 'USERNAME', 'PASSWORD');
    mysql_select_db('DB NAME', $link);

    function test()
    {
        $result = mysql_query("select * from wp_options");
        $data = array();

        while($row = mysql_fetch_array($result))
        {
            $data[] = $row;
        }

        return $data;
    }

    echo "<pre>";
    print_r(test());
    echo "</pre>";

    mysql_close($link);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.