使用OOP和mysql删除查询项

时间:2015-03-16 19:50:06

标签: php mysql

我遇到问题使这段代码有效:

index.php:

    <?php 

include("config.php");

$asd=123;

$db = new db();
$db->connect();


$db->sql('SELECT id,name FROM CRUDClass');
$res = $db->getResult();

foreach($res as $output){
    echo '<div>'.$output['name'].' - <a href="" onclick="'.$db->delete('CRUDClass','id='.$output['id']).'">Delete ID: '.$output['id'].'</a></div><br>';
}

?>

config.php

<?php

    class db{

    private $result = array();
    private $myQuery = "";
    private $numResults = "";
....

public function sql($sql){

        $query = @mysql_query($sql);
        $this->myQuery = $sql; // Pass back the SQL

        if($query){

            // If the query returns >= 1 assign the number of rows to numResults
            $this->numResults = mysql_num_rows($query);

            // Loop through the query results by the number of rows returned
            for($i = 0; $i < $this->numResults; $i++){

                $r = mysql_fetch_array($query);
                $key = array_keys($r);

                for($x = 0; $x < count($key); $x++){

                    // Sanitizes keys so only alpha-values are allowed
                    if(!is_int($key[$x])){

                        if(mysql_num_rows($query) >= 1){

                            $this->result[$i][$key[$x]] = $r[$key[$x]];

                        }else{

                            $this->result = null;

                        }
                    }
                }
            }

            return true; // Query was successful

        }else{

            array_push($this->result,mysql_error());
            return false; // No rows where returned

        }
    }

    // Function to SELECT from the database
    public function select($table, $rows = '*', $join = null, $where = null, $order = null, $limit = null){

        // Create query from the variables passed to the function
        $q = 'SELECT '.$rows.' FROM '.$table;

        if($join != null){
            $q .= ' JOIN '.$join;
        }

        if($where != null){
            $q .= ' WHERE '.$where;
        }

        if($order != null){
            $q .= ' ORDER BY '.$order;
        }

        if($limit != null){
            $q .= ' LIMIT '.$limit;
        }

        $this->myQuery = $q; // Pass back the SQL
        // Check to see if the table exists

        if($this->tableExists($table)){
            // The table exists, run the query
            $query = @mysql_query($q);

            if($query){
                // If the query returns >= 1 assign the number of rows to numResults
                $this->numResults = mysql_num_rows($query);

                // Loop through the query results by the number of rows returned
                for($i = 0; $i < $this->numResults; $i++){

                    $r = mysql_fetch_array($query);
                    $key = array_keys($r);

                    for($x = 0; $x < count($key); $x++){

                        // Sanitizes keys so only alphavalues are allowed
                        if(!is_int($key[$x])){

                            if(mysql_num_rows($query) >= 1){

                                $this->result[$i][$key[$x]] = $r[$key[$x]];

                            }else{

                                $this->result = null;

                            }
                        }
                    }
                }

                return true; // Query was successful

            }else{

                array_push($this->result,mysql_error());
                return false; // No rows where returned

            }

        }else{

            return false; // Table does not exist

        }
    }

    // Function to insert into the database
    public function insert($table,$params=array()){

        // Check to see if the table exists
         if($this->tableExists($table)){

            $sql='INSERT INTO `'.$table.'` (`'.implode('`, `',array_keys($params)).'`) VALUES ("' . implode('", "', $params) . '")';
            $this->myQuery = $sql; // Pass back the SQL

            // Make the query to insert to the database
            if($ins = @mysql_query($sql)){

                array_push($this->result,mysql_insert_id());
                return true; // The data has been inserted

            }else{

                array_push($this->result,mysql_error());
                return false; // The data has not been inserted

            }

        }else{

            return false; // Table does not exist

        }
    }

    //Function to delete table or row(s) from database
    public function delete($table,$where = null){

        // Check to see if table exists
         if($this->tableExists($table)){

            // The table exists check to see if we are deleting rows or table
            if($where == null){

                $delete = 'DELETE '.$table; // Create query to delete table

            }else{

                $delete = 'DELETE FROM '.$table.' WHERE '.$where; // Create query to delete rows

            }

            // Submit query to database
            if($del = @mysql_query($delete)){

                array_push($this->result,mysql_affected_rows());
                $this->myQuery = $delete; // Pass back the SQL
                return true; // The query exectued correctly

            }else{

                array_push($this->result,mysql_error());
                return false; // The query did not execute correctly

            }

        }else{

            return false; // The table does not exist

        }
    }

....

    public function getResult(){
        $val = $this->result;
        $this->result = array();
        return $val;
    }

    //Pass the SQL back for debugging
    public function getSql(){
        $val = $this->myQuery;
        $this->myQuery = array();
        return $val;
    }

    //Pass the number of rows back
    public function numRows(){
        $val = $this->numResults;
        $this->numResults = array();
        return $val;
    }
}

?>

问题在于,当我尝试删除列表中的项目时,它会删除数据库中的所有项目。我可以使用链接中的$ get [&#39; id&#39;]方法在单独的文件中正确删除项目,但我不明白为什么当前的代码会在foreach中搞砸了?

2 个答案:

答案 0 :(得分:0)

在此:

 echo '<div>'.$output['name'].' - <a href="" onclick="'.$db->delete('CRUDClass','id='.$output['id']).'">Delete ID: '.$output['id'].'</a></div><br>';

您希望在触发onclick事件时调用delete方法,但这不会发生。

目前,访问index.php时将调用delete方法。

要使其正常工作,请将<a>标记更改为链接到其他php文件并将调用放在其中的delete方法中,或者您可以在链接中使用相同的php文件并使用?查询链接。

答案 1 :(得分:0)

到底是什么,你完全误解了PHP xD

让我们说你的代码insert, delete,...按照你想要的方式工作,而不是:

foreach($res as $output){
    echo '<div>'.$output['name'].' - <a href="" onclick="'.$db->delete('CRUDClass','id='.$output['id']).'">Delete ID: '.$output['id'].'</a></div><br>';
}

...生成一些<div>Name <a href="" onclick="'true'">Delete ID: 1</a></div><br>代码。创建后,每个delete都被调用,因此你的表是空的。

PHP仅在服务器上生成输出并将其发送回客户端。你必须写这样的代码:

foreach(...) {
?>
   <div><a href="delete.php?id=<?=$output['id']?>">delete me</a></div>
<?php
}

然后在delete.php中,您$_GET['id']并致电delete

总而言之,阅读http://en.wikipedia.org/wiki/SQL_injection永远不会太早。这意味着您必须在将id参数插入查询之前将其转义。我建议使用准备好的陈述。

但首先,了解PHP的作用:)。您无法将PHP回调实现为HTML或您尝试过的内容。