AshKan
AshKan

Reputation: 829

clear all the entries from a table with php

I want to clear all the entries from one table in MySQL with php I tried this:

<?php
// Create connection
        $con=mysqli_connect("localhost","username","password","dbName");

// Check connection
        if (mysqli_connect_errno($con))
        {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }    

    $sql = "TRUNCATE TABLE tableName";
    mysqli_query($sql);
?>

but it didn't work. why?

Upvotes: 6

Views: 18043

Answers (3)

hek2mgl
hek2mgl

Reputation: 157967

This is a typo. You used mysql_query() instead of mysqli_query(). Change

mysql_query($sql);

to:

mysqli_query($con, $sql);

Also note that the param lists of both functions differ. mysqli_expects() a connection handle as it's first param.

Upvotes: 7

siddharth
siddharth

Reputation: 231

After creating a connection using "mysqli", you are trying to delete all the records in "dbName" using mysql_query.

Change the code to something like,

<?php
    // Create connection
    $con=mysqli_connect("localhost","username","password","dbName");
    // Check connection
    if (mysqli_connect_errno($con))
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }    
    $sql = "TRUNCATE TABLE tableName";
    mysqli_query($con, $sql) or die(mysqli_error());
?>

See if this works and let me know.

Upvotes: 2

MattP
MattP

Reputation: 2863

Firstly check for any error messages that may give a clue, there are some restrictions that can prevent TRUNCATE from working. Also ensure it's not a typo with the mysql/mysqli functions as in your question.

If the table isn't huge, or performance isn't critical then simply try:

$sql = "DELETE * FROM tableName";

Upvotes: -1

Related Questions