如何在浏览器中显示数据库中的记录?

时间:2010-09-02 13:55:52

标签: php sql

我是PHP和SQL的新手,我正在尝试在浏览器中显示数据库中的记录。我首先尝试测试当用户从下拉菜单中选择“SELECT”时如何显示记录。

创建了一个名为selectById()

的函数
// function selectById ---------------------------------------------------------------------------------------------
        function selectById($pUInput) {
            echo "select by id is being called" . "<br/>";

            $query = mysql_query("SELECT * FROM tblStudents 
                                WHERE id='$pUInput[0]'");
            $result = $db->query($query);

            if (!$row = mysql_fetch_array($sql))
                  {
                  die('Error: ' . mysql_error());
                  } else {
                  display($query, $result);
                  }
                //echo "selected" . "<br/>";
                //echo $pUInput[0];

        }

selectById()内部 - 调用display()。创建显示功能以显示数据库的记录。现在我正在试图弄清楚如何使两个功能正常工作。

// function display -------------------------------------------------------------------------------------------------
function display($pDisplay, $pResult) {
    echo "display is being called";
    $num_results = $results->numRows();

    //display each returned row
    for($i=0; $i<$num_results; $i++) {
        $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
        echo stripslashes($row[id]);
        echo stripslashes($row[first_name]);
        echo stripslashes($row[last_name]);
        echo stripslashes($row[major]);
        echo stripslashes($row[year]);      

    }

    }

PHP代码:

//Call function mainline
mainline();

// Declare the function mainline
function mainline() {

    $uInput = getUserInput();
    echo "Info from mainline...Action:" . " " . $uInput[5] . "<br/>";
    $connectDb = openConnect(); // Open Database Connection
    selectDb($connectDb); // Select Database
    doAction($uInput);
    //display();
    //closeConnect();

}

//Declare function getUserInput ------------------------------------------------------------------------------------
function getUserInput() {

    echo "In the function getUserInput()" . "<br/>";

    // Variables of User Input
    /*$idnum = $_POST["idnum"];              // id (NOTE: auto increments in database)
    $fname = $_POST["fname"];             // first name
    $lname = $_POST["lname"];            // last name
    $major = $_POST["major"];           // major
    $year = $_POST["year"];            // year
    $action = $_POST["action"];       // action (select, insert, update, delete)*/

    $idnum = mysql_real_escape_string($_POST["idnum"]);
    $fname = mysql_real_escape_string($_POST["fname"]);
    $lname = mysql_real_escape_string($_POST["lname"]);
    $major = mysql_real_escape_string($_POST["major"]);
    $year = mysql_real_escape_string($_POST["year"]);
    $action = mysql_real_escape_string($_POST["action"]);


    $userInput = array($idnum, $fname, $lname, $major, $year, $action);

    return $userInput;
}

// function doAction ----------------------------------------------------------------------------------------------
function doAction($pUserInput) {
    echo "In function doAction()" . "<br/>";

    if ($pUserInput[5] == "insert") {       
        //checkStudentFields();
        insert($pUserInput);    
        //echo "I need to insert!";

    } elseif ($pUserInput[5] == "select") {
        selectById($pUserInput);
        echo "I need to select";

    } elseif ($pUserInput[5] == "update") {
        update($pUserInput);
        echo "I need to update";

    } elseif ($pUserInput[5] == "delete") {
        deleteById($pUserInput);
        echo "I need to delete";

    }

}



// Create a database connection ------------------------------------------------------------------------------------
function openConnect() {
    $connection = mysql_connect("localhost", "root_user", "password");
        echo "Opened Connection!" . "<br/>";    
    if(!$connection) {
        die("Database connection failed: " . mysql_error());
    }
    return $connection;
}

// Select a database to ------------------------------------------------------------------------------------------- 
function selectDb($pConnectDb) {
    $dbSelect = mysql_select_db("School", $pConnectDb);
    if(!$dbSelect) {
        die("Database selection failed: " . mysql_error());
    } else {
    echo "You are in the School database! <br/>";   
    }

}

// Close database connection ------------------------------------------------------------------------------------
function closeConnect() {
    mysql_close($connection);
}

// function selectById ---------------------------------------------------------------------------------------------
function selectById($pUInput) {
    echo "select by id is being called" . "<br/>";

    $query = mysql_query("SELECT * FROM tblStudents 
                        WHERE id='$pUInput[0]'");
    $result = $db->query($query);

    if (!$row = mysql_fetch_array($sql))
          {
          die('Error: ' . mysql_error());
          } else {
          display($query, $result);
          }
        //echo "selected" . "<br/>";
        //echo $pUInput[0];

}


// function insert -------------------------------------------------------------------------------------------------
function insert($pUInput) {     
    $sql="INSERT INTO tblStudents (first_name, last_name, major, year)
          VALUES
         ('$pUInput[1]','$pUInput[2]','$pUInput[3]', '$pUInput[4]')";

        if (!mysql_query($sql))
          {
          die('Error: ' . mysql_error());
          }
        echo "1 record added";
}

// function update -------------------------------------------------------------------------------------------------
function update($pUInput) {
    $sql = "UPDATE tblStudents 
        SET first_name = '{$pUInput[1]}',
            last_name = '{$pUInput[2]}', 
            major = '{$pUInput[3]}', 
            year = '{$pUInput[4]}'
        WHERE id = '{$pUInput[0]}'";

    if(!mysql_query($sql))
    {
        die('Error: ' . mysql_error());
    }
    echo "1 record update";

}

// function delete -------------------------------------------------------------------------------------------------
function deleteById($pUInput) {
        // call select();
        $sql="DELETE FROM tblStudents WHERE id='$pUInput[0]'";
        $result=mysql_query($sql);

        if($result){
            echo "Deleted Successfully";
        }else {
            echo "Error";
        }       
}

// function display -------------------------------------------------------------------------------------------------
function display($pDisplay, $pResult) {
    echo "display is being called";
    $num_results = $results->numRows();

    //display each returned row
    for($i=0; $i<$num_results; $i++) {
        $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
        echo stripslashes($row[id]);
        echo stripslashes($row[first_name]);
        echo stripslashes($row[last_name]);
        echo stripslashes($row[major]);
        echo stripslashes($row[year]);      

    }

}

SQL语法

CREATE TABLE `tblStudents` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(30) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `major` varchar(40) NOT NULL,
  `year` date NOT NULL,
  PRIMARY KEY (`id`)
)

1 个答案:

答案 0 :(得分:1)

我不确定我是否遗漏了某些东西,但是看看“selectById”的逻辑,我无法确定它应该如何实际工作。

最大的问题是我无法分辨出你从哪里获得了一些变量,看起来你正在以错误的方式使用它们中的一些。

首先,你打电话

$ query = mysql_query(“SELECT * FROM tblStudents WHERE id ='$ pUInput [0]'”);

哪个应该在'$ query'变量中创建资源。这是一种简单的,非PDO的查询方式。然而,重要的是要意识到“$ query”中的内容是一种资源,所以如果你打印出来,你会得到一些像“资源ID#6”这样的标识符。

正确 - 那么你似乎做了相同的事情(即执行查询),但这次使用PDO,并且你没有传递'$ db'对象一个字符串(这是第一个参数所要求的) ,而是你传递一个RESOURCE - 其字符串表示不完全有效的SQL;)

另一个问题是你实际上没有在任何地方定义$ db对象......所以这也是一个问题。

我认为主要的问题是你正在使用一种混搭的PDO和直接的mysql数据库访问。也许看看文档中的快速调整,以便清楚地了解它们之间的区别。 (对不起,我是新用户,无法发布实际链接)

http://www.php.net/manual/en/book.pdo.php http://www.php.net/manual/en/book.mysql.php

我希望我不会误解你的问题。但是,如果我正确地阅读您的代码,我认为您对使用这两种(不同的)访问数据库的方法感到有些困惑。