2017-08-14 63 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;