2017-08-14 66 views
0

我想用這段代碼來完成兩件事情。我使用INSERT PHP Plugin將PHP直接寫入WP頁面。PHP和MySQL WP

1)查詢MySQL數據庫並將結果從一列返回到四列。

2)使每個結果都是它自己的超鏈接,它將用戶引導到在該頁面上運行新查詢的新WP頁面。

我能夠得到查詢來顯示結果,甚至將這些結果變成動態超鏈接,但我無法取得格式。現在它只是將結果返回到一列中。這裏是我有:

[insert_php] 

$servername = "localhost"; 
$username = "login"; //edited for privacy 
$password = "password"; //edited for privacy 
$database = "database"; //edited for privacy 

// Create connection 
$conn = new mysqli($servername, $username, $password, $database); 

// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 
echo "Connected successfully"; 

//get results from database 
$result = mysqli_query($conn,"SELECT mine FROM mines ORDER BY mine"); 
$all_property = array(); //declare an array for saving property 

//showing property 
echo '<table class="data-table"> 
     <tr class="data-heading">'; //initialize table tag 

while ($property = mysqli_fetch_field($result)) { 
    echo '<td>' . $property->name . '</td>'; //get field name for header 
    array_push($all_property, $property->name); //save those to array 
} 
echo '</tr>'; //end tr tag 

//showing all data 

while ($row = mysqli_fetch_array($result)) { 
    echo "<tr>"; 
    foreach ($all_property as $item) { 
     echo "<td><a href='urlhere/$row[$item]'>".$row[$item]. "</a>"."</td>"; //get items using property value 
    } 
    echo '</tr>'; 
} 
echo "</table>"; 

[/insert_php] 

感謝您的任何幫助,您可以提供。

我想結果看起來像這樣(每一個爲超鏈接):

Image link below

+0

您的查詢只抓住一列。你如何看待4列? – Eric

+0

你能展示你期待什麼格式嗎? –

+0

Eric - 我想將結果格式化爲頁面上的四列。 – user2267031

回答

0

我能來解決這一問題。仍然沒有得到正確的超鏈接的結果,但現在陣列正在填充超過四列。這裏是我的代碼:

$sql = "SELECT mine FROM mines ORDER by mine"; 
$result = mysqli_query($conn, $sql); 

if ($result) { 
    $data = array(); 
    while($row = $result->fetch_assoc()) { 
     $data[] = $row['mine']; 
    } 
} 

if (is_array($data) && count($data)) { // if array's not empty, create HTML 

     //create a table & header row 
     $htmlout="<table><tr> 
     <th colspan='4'>Mine</th></tr> 
     <tr> 
     "; 

     $counter = 1; //keep count of data 

     foreach ($data as $mines) { 
     //table cell for datum 
     $htmlout .= "<td>$mines</td>\n"; 

     //rows of 4 
     if ($counter % 4 == 0) { 
      $htmlout .= "</tr>\n<tr>\n"; 
     } 
     $counter++; 
     } 
} 
$htmlout .= "</tr></table>"; 

echo $htmlout;