Frederik Nielsen Frederik Nielsen - 6 months ago 38
SQL Question

truncating table not working

I am working on a PHP script to export/import some database rows from one DB to another.

So far I got this function to make sure the destination table is empty before putting new rows in there:

function truncateTable($conn, $tblname)
{
echo "Truncating..";
$query = $conn->exec("TRUNCATE TABLE $tblname") or die("failed!");
echo "Truncated table $tblname!";
}


However, this is giving me this error:

Call to a member function exec() on a non-object


The connectionstring that gets passed to the function in
$conn
looks like this:

$con2 = new PDO("mysql:host=$dbs2;dbname=$dbd2",$dbu2,$dbp2);


I call the function like this:

truncateTable($con2, "users");


What am I doing wrong?

I am just learning PDO, so forgive me if this is a very basic question.

Answer

Try this instead, you are passing $conn in to the method, not $q:

function truncateTable($conn, $tblname)
{
    echo "Truncating..";
    $query = $conn->exec("TRUNCATE TABLE $tblname") or die("failed!");
    echo "Truncated table $tblname!";
}

To fix the other issue, use query() instead of exec() :)