New to PDO. Here is my function. We are connected to the database and everything is working but this function when called is killing off the rest of PHP to be executed. Obviously something is wrong with it.

$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
        global $dbh;

        /*** set the error reporting attribute ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

function selectall($table){
            $stmt = $dbh->prepare("SELECT * FROM :table");
            $stmt->bindParam(':table', $table, PDO::PARAM_STR,20);
            $stmt->execute();
            $result = $stmt->fetchAll();
            return $result;
        }

Called on a page like this:

<?php $telephones = selectall('telephone'); foreach($telephones as $telephones) { echo $telephone['title'].', '; } ?>

/// EDIT - I have tried all of your methods and the function is still breaking when called on the page. Here is the entire code. Slightly modified for testing purposes.

try { 

        $dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);

        /*** set the error reporting attribute ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $sql = "SELECT * FROM system";
        foreach ($dbh->query($sql) as $row)
            {
            $url = $row['url'];
            $election = $row['election'];
            $election_date = $row['election_date'];
            $sitename = $row['sitename'];
            }


        //FUNCTION

        function selectall($table){
            global $dbh;
             $sql = "SELECT * FROM telephone";
            foreach ($dbh->query($sql) as $row){
                print $row['title'] .' - '. $row['name'] . '<br />';
            }
        }


        /** close database connections **/
        $dbh = null;

    }

    catch(PDOException $e) { 

        echo $e->getMessage(); 

    }

The code outside the function ie. the one reflecting the table system is working perfectly Yet the one inside the function when called as a function later is killing off everything after it is called and is not executing.

有帮助吗?

解决方案

Your second line generates a fatal error, when you're trying to use an undefined variable ($dbh) as an object.

You need to import it from the global scope like this:

global $dbh;

or pass it as a parameter to the function.

After you fix this, your code still won't work, as you cannot use parameters for identifiers (table or column names, or even in limit and offset). Unfortunately you have to resort to string concatenation there.

其他提示

I think the problem is: $telephones as $telephones

Try this:

$telephones = selectall('telephone'); foreach($telephones as $telephone) { echo $telephone['title'].', '; }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top