2013-07-14 176 views
0

我会再次尝试询问此问题。希望这次更有意义!从MYSQL查询的结果中循环并插入表中

我的网页上有一个用户可编辑的单元格。我想连接到MYSQL数据库并搜索字段以输入到该单元格中的文本,对于找到的每个结果,我想向表中添加一个新行。我知道如何连接到数据库,我知道如何通过html创建查询。我不知道并希望得到一些指导,是循环遍历每个结果并使用变量完成查询的机制!

我添加的行

<script> 
function getsearchresults() 
{ 
var table=document.getElementById("myTable"); 
var row=table.insertRow(-1); 
var cell1=row.insertCell(0); 
var cell2=row.insertCell(1); 
var cell3=row.insertCell(2); 
var cell4=row.insertCell(3); 
cell1.innerHTML= Variable1heremaybe?; 
cell2.innerHTML="Variable2heremaybe?; 
cell3.innerHTML="Variable3heremaybe?; 
cell4.innerHTML="Variable4heremaybe?; 
} 
</script> 
</head> 
<body> 

<table style="margin-top:350px; margin-left:25px;" id="myTable" border="1"> 
    <tr> 
    <td>column1 <div style="width: 100px"> </div></td> 
    <td>column2 <div style="width: 100px" > </div></td> 
    <td>column3 <div style="width: 100px" > </div></td> 
    <td>column4 <div style="width: 100px" > </div></td> 

</table> 

查询搜索代码

<?php 
// Create connection 
$con=mysqli_connect("bla","blabla","blablabla","blablabla"); 

// Check connection 
if (mysqli_connect_errno($con)) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

SELECT `Table1`.`Column1` 
FROM Table1 
WHERE (`Table1`.`Column1` Variableheremayb?) 
ORDER BY `Table1`.`Column1` ASC 
?> 

任何帮助将不胜感激代码!

回答

0

,你可以这样做: 这里我假设你已经成功地连接到数据库

//first execute the query 

$result = mysqli_query("Your query"); 

//then fetch the result of each row using a loop 

while($row = mysqli_fetch_assoc($result)) 
{ 
    //here you can display the data or store it in a variable or anything else you want 
    // for example you want to display it inside div tag. 
    echo "<div>".$row["column1"]."</div>"; 
    echo "<div>".$row["column2"]."</div>"; 
    //and so on 

} 

我希望这能有一定的帮助。

+0

谢谢!然而,我似乎无法得到一个新的行添加到表中,而在while语句中,因此显然不能添加结果。我不熟悉。$ row [“column1”],这是否假设我们的活动结果的column1中的数据填充了“mytable”中的新行? [链接](http://www.w3schools.com/jsref/met_table_insertrow.asp)这是我正在寻找的影响,但与我们的查询每个结果! – Phil

+0

你是否熟悉ajax –

+0

否:(哈哈,有点noob我很害怕!我很新编程 – Phil

0

首先我建议在HTML中将你的行单元命名为cell[]。它们将作为一个数组发布,更容易循环。

<table> 
    <tr> 
    <td><input type="text" name="cell[]" /></td> 
    <td><input type="text" name="cell[]" /></td> 
    <td><input type="text" name="cell[]" /></td> 
    </tr> 
</table> 

服务器侧部:

<?php 

// Connect to MySQL 
... 

// Validate your form inputs 
... 
$cells = yourInputFilter($_POST['cell']); 
... 

// Build query 
$cellSql = implode(',', $cells); 

$sql = "SELECT * 
     FROM table1 
     WHERE column1 IN ($cellSql) 
     ORDER BY column1";