1

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Frederik
  • 632
  • 4
  • 16
  • 34

4 Answers4

4

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() :)

user1909426
  • 1,658
  • 8
  • 20
3

One possible culprit may be DB permissions--i.e. does the MySQL user profile have sufficient privileges to TRUNCATE a table? Intuitively that might seem like the same thing as DELETE, but it's not. TRUNCATE requires DROP privileges (http://dev.mysql.com/doc/refman/5.1/en/truncate-table.html).

One frustrating thing about mysqli_query() is that if the web user is not allowed to DROP tables, the "...or die()" part doesn't execute--kind of passive-aggressive, IMO. ;~)

2

The argument in the function is $conn, not $q.

Saty
  • 22,443
  • 7
  • 33
  • 51
Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
-1

This worked for me:

$clean2 = $db->query( "TRUNCATE TABLE `table`");

Nice and simple.