在循环php中命中数据库

时间:2018-11-27 06:22:36

标签: php mysql database-connection

我对PHP非常陌生。我只是创建一个简单的页面,该页面从数据库中获取数据并生成XML。有两个表,一个具有竞争对手的表,第二个具有针对这些竞争对手的排名,因此我能够获取候选数据,并且当我循环访问此数据并尝试再次循环进入数据库时​​,出现以下错误:< / p>

  

未定义变量:mysqli输入

     

致命错误:在null中调用成员函数query()

我尝试了几件事,但是没有用。这是我的代码:

<?php
/** create XML file */ 
$mysqli = new mysqli("localhost", "root", "******", "****");
/* check connection */
if ($mysqli->connect_errno) {
   echo "Connect failed ".$mysqli->connect_error;
   exit();
}else{
}
$query = "select * from competitors where eventid=290 order by 1 desc LIMIT 0, 10;";
$booksArray = array();
if ($result = $mysqli->query($query)) {
/* fetch associative array */
   while ($row = $result->fetch_assoc()) {
   array_push($booksArray, $row);
  }
   if(count($booksArray)){
createXMLfile($booksArray);

 }
/* free result set */
   $result->free();
}
function createXMLfile($booksArray){
   $filePath = 'book.xml';
   $dom     = new DOMDocument('1.0', 'utf-8'); 
   $root      = $dom->createElement('books'); 
   for($i=0; $i<count($booksArray); $i++){
$eventid        =  $booksArray[$i]['eventid'];  
 $fee      =  $booksArray[$i]['fee']; 
$competitorid_system    =  $booksArray[$i]['competitorid'];
$datetimeentered     =  $booksArray[$i]['datemodified']; 
// $bookISBN      =  $booksArray[$i]['ISBN']; 
//  $bookCategory  =  $booksArray[$i]['category'];  
$book = $dom->createElement('book');
 $book->setAttribute('eventid', $eventid);
$name     = $dom->createElement('fee', $fee); 
$book->appendChild($name); 
$author   = $dom->createElement('competitorid_system', $competitorid_system); 

 $book->appendChild($author); 

 $price    = $dom->createElement('datetimeentered', $datetimeentered); 

$book->appendChild($price); 

// fetch other data
$query = "select * from ranking where eventid=290 and competitorid=".$competitorid_system;;

 echo "Query".$query;
   //exit();
$booksRankingArray = array();
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
array_push($booksRankingArray, $row);
}
if(count($booksRankingArray)){
createXMLfile($booksRankingArray);
 }
/* free result set */
$result->free();
}
$root->appendChild($book);
}
$dom->appendChild($root); 
$dom->save($filePath); 
} 
/* close connection */
$mysqli->close();

1 个答案:

答案 0 :(得分:3)

$mysqli变量超出了createXMLfile()的范围。

  

变量的范围是定义变量的上下文。在大多数情况下,所有PHP变量都只有一个作用域。这个单一范围也涵盖了包含和必需的文件。

Please refer to the PHP Manual to understand the variable scope

解决问题,将功能签名更改为

function createXMLfile($mysqli, $booksArray)
{ 
    // … rest of code …
}

然后将变量从外部范围传递到函数范围:

$mysqli = new mysqli("localhost", "root", "******", "****");
$booksArray = array();    
createXMLfile($mysqli, $booksArray);

您还可以使用全局变量从全局范围提取变量:

function createXMLfile($booksArray)
{ 
    global $mysqli;
    // … rest of code …    
}

But using global variables is generally discouraged,因为它会导致代码紧密耦合,并使代码不易推理。

相关问题