如何在一个PHP函数中使用多个查询

时间:2014-03-13 09:14:28

标签: php mysql sql function

大家好我只是想知道如何运行两个sql查询运行两个sql查询我的功能此刻是与数据库连接下方的代码位于页面顶部所以我不需要每次我的整页代码是:

来纠正连接
<?php
class SelectList
{
    protected $conn;

        public function __construct()
        {
            $this->DbConnect();
        }

        protected function DbConnect()
        {
            include "db_config.php";
            $this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
            mysql_select_db($db,$this->conn) OR die("can not select the database $db");
            return TRUE;
        }


        public function ShowCategory()
        {
            $sql = "SELECT subject.subject_id,subject.description,COUNT(media.subject_id) as media_count\n"
                 . "from subject LEFT OUTER JOIN media ON subject.subject_id = media.subject_id \n"
                 . "WHERE verified = 1\n"
                 . "GROUP BY subject.subject_id,subject.description ORDER BY subject.description ";
            $res = mysql_query($sql,$this->conn);
            $category = '<option value="%">Subject</option>';
            while($row = mysql_fetch_array($res))
            {
                $category .= '<option value="' . $row['subject_id'] . '">' . $row['description']. '...('.$row['media_count'].')</option>';
            }
            return $category;
        }

        public function ShowType()
        {
           $sql =  "SELECT section.section_id,section.description,section.subject_id,COUNT(media.section_id) as media_count
                    FROM section LEFT OUTER JOIN media ON section.section_id = media.section_id 
                    AND section.subject_id = media.subject_id
                    WHERE section.subject_id={$_POST['id']} AND verified = 1
                    GROUP BY section.section_id,section.description";
            $res = mysql_query($sql,$this->conn);
            $type = '<option value="%">choose...';
            while($row = mysql_fetch_array($res))
            {
                $type .= '<option value="' . $row['section_id'] . '">' . $row['description']. '...('.$row['media_count'].') </option>';
            }
            return $type;
        }

         public function ShowPrinciple()
        {
            $sql = "SELECT principle.principle_id,principle.description,principle.section_id,COUNT(media.principle_id) as media_count
                    FROM principle 
                    LEFT OUTER JOIN media ON principle.principle_id = media.principle_id 
                    AND principle.section_id = media.section_id 
                    WHERE principle.section_id={$_POST['id']} AND verified = 1
                    GROUP BY principle.principle_id,principle.description";
            $res = mysql_query($sql,$this->conn);
            $principle = '<option value="%">choose...</option>';
            while($row = mysql_fetch_array($res))
            {
                $principle .= '<option value="' . $row['principle_id'] . '">' . $row['description'].  '...('.$row['media_count'].') </option>';
            }
            return $principle;
        }

        public function GetResults()
        { 
        //$vars = $_POST["comboboxselections"]; // this gets comboboxselections from index.php

            list($subjectID, $sectionID, $principleID) = explode('#', $_POST["comboboxselections"]);

           $box = ""; // placeholder for the html results to be returned to 
           $sql = "SELECT media_id,title,blurb 
                    FROM media 
                    WHERE subject_id = $subjectID AND section_id = $sectionID AND principle_id= $principleID AND verified = 1"; // sql query 


           $hasprintedrecords = false; // capture records if there are no records printed to screen 
           $res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
            while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
            {
                $hasprintedrecords = true;// if there are records this equals true if not equals false 
                $box .= '

                <div style="margin-top:5px;height:120px;padding:0px;"id="Video">

                <div style="width:185px;height:105px;float:left;" id="VideoImage">
                <img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
                </div>

                <div style="float:right;padding-left:5px;width:72%;font-size:15px;padding-top:0px;font:verdana,sans-serif;" id="text">
                <div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
                <a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a> 
                <div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
                <div  id="Downloads">
                <a href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">
                <img style="width:100px; margin-left:-10px;margin-top:10px;" src="images/download.jpg">   
                </a>
                </div>
                </div>
                </div>'; // if results are available then display to screen 
            }
            if ( $hasprintedrecords == false) // if there are no results then function below is run  
            { 
            $box .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen 
            }
            return $box; // returns results to the screen
        }

        public function ShowJobRole() { 

        $sql = "SELECT jobrole_id,description
        FROM jobrole ";
            $res = mysql_query($sql,$this->conn);
            $jobrole = '<option value="%">Job role</option>';
            while($row = mysql_fetch_array($res))
            {
                $jobrole .= '<option value="' . $row['jobrole_id'] . '">' . $row['description'] . '...('.$row['media_count'].'</option>';
            }
            return $jobrole;
        } 

        public function ShowCareer() { 

        $sql = "SELECT career_id,description FROM career WHERE jobrole_id={$_POST['id']}";
        $res = mysql_query($sql,$this->conn);
        $career = '<option value="%">Career</option>';
        while($row = mysql_fetch_array($res))
        {
            $career .= '<option value="' . $row['career_id'] . '">' . $row['description'] . '</option>';
        }
        return $career;
    } 
        public function get_job () { 

            //$vars1 = $_POST["comboboxselections1"]; // this gets comboboxselections from index.php

            list($jobroleID, $careerID) = explode('#', $_POST["comboboxselections1"]);

            $res = mysql_query($sql,$this->conn);

            $box = ""; // placeholder for the html results to be returned to 
            $sql = "SELECT title,blurb,m.media_id
                    FROM media_career_crossref mcc
                            INNER JOIN media m ON m.media_id = mcc.media_id 
                    WHERE mcc.jobrole_id = $jobroleID AND mcc.career_id = $careerID";


            $hasprintedrecords = false; // capture records if there are no records printed to screen 

            $res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
            while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
            {
                $hasprintedrecords = true;// if there are records this equals true if not equals false 
             $box .= '
            <div style="margin-top:5px;height:120px;padding:0px;"id="Video">

                <div style="width:185px;height:105px;float:left;" id="VideoImage">
                <img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
                </div>

                    <div style="float:right;padding-left:5px;width:72%;font-size:15px;padding-top:0px;font:verdana,sans-serif;" id="text">
                <div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
                <a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a> 
                <div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
                <div  id="Downloads">
                <a style="width:100px; margin-left:-10px;margin-top:10px;" href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">
                <img style="width:110px;" src="images/download.jpg">                  
                </a> 

                </div>
                </div>
                </div>'; // if results are available then display to screen 
                }
            if ( $hasprintedrecords == false) // if there are no results then function below is run  
            { 
            $box .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen 
            }
            return $box; // returns results to the screen
        }

         public function Unverified()
        { 
           $unverified = ""; 
           $sql = "SELECT * 
                    FROM media 
                    WHERE verified = 0 "; // sql query 
           $box = "";
           $hasprintedrecords = false; // capture records if there are no records printed to screen 
           $res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
            while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
            {
                $hasprintedrecords = true;// if there are records this equals true if not equals false 
                $unverified .= '

                <div style="margin-top:5px;height:120px;padding:0px;"id="Video">

                <div style="width:185px;height:105px;float:left;" id="VideoImage">
                <img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
                </div>

                <div style="float:right;padding-left:5px;width:72%;font-size:12px;padding-top:0px;font:verdana,sans-serif;" id="text">
                <div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
                <a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a> 
                <div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
                <div  id="Downloads">
                <a id="Download" href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">Download</a>
                </div>
                </div>
                </div>'; // if results are available then display to screen 
            }

           if ( $hasprintedrecords == false) // if there are no results then function below is run  
            { 
            $unverified .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen 
            }
            return $unverified; // returns results to the screen
        }


            public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) { 
            $sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid) 
               VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
            $this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
            mysql_query($sql, $this->conn);
                    (return mysql_affected_rows($this->conn) > 0);
            }

            public function addMediaCrossRef($Job, $Career, $Uniq_id) {
            $sql = "INSERT INTO media_career_crossref (media_id, jobrole_id, career_id, verified, media_uniqid) 
            VALUES (NULL, '".$Job."', '".$Career."', '0', '".$Uniq_id."')";
            mysql_query($sql, $this->conn);
                    (return mysql_affected_rows($this->conn) > 0);
            }


        }
$opt = new SelectList();
?>

上面是我目前为此网页获取的完整代码,最新功能是页面上的最后一个。

这是从不同页面调用函数的方式

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) 
    {
        echo "File is valid, and was successfully uploaded.\n"; 

        include "select.class.php";
        /*$opt->addNewMediaCrossRef($Job, $Career, $Uniq_id);*\ /* me trying to call both functions at once this didnt work either*/

        $opt->addNewRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id);


        }

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

另一个答案可能已经声明您可以使用MySQLi的多查询选项,并且正如我评论的那样,您可以对第一个语句使用*_query()一次,对第二个语句使用第二次。但是,您正在制定该方法的单一责任原则。如果你想链接到一个中的动作,用不同的方法将它们分开并在内部调用。

public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) { 
       $sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid) 
               VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
       $this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
       return yourQueryFunction($sql, $this->conn); 
}

public function addMediaCrossRef($Job, $Career, $Uniq_id) {
    $sql = "INSERT INTO media_career_crossref (media_id, jobrole_id, career_id, verified, media_uniqid) 
         VALUES (NULL, '".$Job."', '".$Career."', '0', '".$Uniq_id."')";
    return yourQueryFunction($sql, $this->conn);
}

通常方法不会返回query()返回值,尤其是在插入/更新

我更愿意:

public function addNewMediaRecord($all_the_params) {
    $sql = ".....";
    yourQueryFunction($sql);
    $this->chainedMethod($params);
    return yourFunctionforAFFECTED_ROWS() > 0;
}

因此,如果受影响的行大于零(成功插入),它将返回布尔值。


此外,您还可以更好地包装数据库函数,以便在需要时更轻松地在库之间切换。

E.g:

class Database {

    private $_host;
    private $_user;
    private $_pass;
    private $_db;

    private $_conn;

    public function __construct($host, $user, $pass, $db) {
        $this->_host = $host;
        $this->_user = $user;
        $this->_pass = $pass;
        $this->_db = $db;

        $this->connect();
    }

    private function connect() {
        $this->_conn = mysqli_connect($this->_host, $this->_user, $this->_pass, $this->_db)
                or die(mysqli_error($this->_conn));
    }

    public function query($query) {
        return mysqli_query($this->_conn, $query);
    }

    public function affectedRows() {
        return mysqli_affected_rows($this->_conn);
    }

class TheClassWhereYourMethodsYouHaveShownAre {

    protected $_db;    

    public function __construct() {
        $this->_db = new Database('host', 'user', 'pass', 'db');
    }


    public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) { 
           $sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid) 
               VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
           $this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
           $this->_db->query($sql);
           return $this->_db->affectedRows > 0;
    }

答案 1 :(得分:0)

mysql_query()发送一个唯一的查询 您可以使用mysqli_multi_query函数,但使用PHP mysqli扩展。

但是,如果你已经死了设置使用mysql_query那么试试这个 -

<?php
$str="query1;query2;"; // 

$query = explode(';',$str);

// Run the queries
foreach($query as $index => $sql)
{
   $result = mysql_query($sql);    
   // Perform an additional operations here
}
?>