2010-12-16 120 views
0

我有幾個問題在這裏,所以任何幫助將不勝感激。我在這裏有三頁。需要幫助mysqli PHP選擇語句

//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; 

如果這是可能的。誰能幫幫我嗎?

回答

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; 
} 
+0

的感謝!當從第3頁調用函數時,我應該如何綁定這些參數?我應該在第2頁中這樣做,但在第3頁中設置變量?變量會改變。例如,只需將第一行代碼添加到第2頁,然後在第3頁中調用函數時設置變量。例如:Page - 3 - $ start = 0; $ end = 5; selectInfo(); – mcbeav 2010-12-16 09:10:31