需要帮助mysqli PHP选择Statement

时间:2010-12-16 08:52:22

标签: php mysqli prepared-statement

我在这里有几个问题,所以任何帮助都将不胜感激。我这里有三页。

//Page 1 - Constants

$dbhost = "database.url.com";  //Just made up
$dbname = "dbname";
$dbuser = "dbuser";
$dbpass = "123456";


//Page 2 - The Function

//This is where i need to write the function select information from the database.

include ("include/page1.php");
$DBH = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
function selectInfo(){
$stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
}
//This function obviously is not complete because I keep recieving different error messages. I guess i cannot figure out how to write a prepared select statement. Need some help here.


//Page 3 - Where the function is called and where the user would be
 include ("include/page2.php");

//need to be able to call the function here with variables set.

$start = 0;
$end = 5;
selectInfo();
echo the data that i need in the database.

这可能看起来像一个完整的混乱,但希望你能得到我想在这里做的想法。我希望能够获取数据,以便我可以显示它像

echo $stmt->title;
echo $stmt->id;

如果可以的话。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

mysqli_prepare文档中解释了您需要的所有内容。

答案 1 :(得分:1)

您需要在mysqli对象上执行bind_paramexecute方法:

$DBH->bind_param("ii", $start, $end);

然后执行声明:

$DBH->execute();

仔细查看mysqli API

来自php.net第一个例子。

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

    /* execute statement */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

@mcbeav

你应该改变你的功能:

function selectInfo(){
    $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
}

对于这样的事情:

function selectInfo($limit, $offset){
    $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();

    // Other stuff to get your values from this query
    ...

    // Return the object with the results
    return $values;
}