我目前正在开发我的计算项目,该项目将允许用户创建无限数量的文件。我目前所坚持的是检索这些值以让用户选择一个,这是我的代码:
function DispMonth(){
$dateList=GetDates($_Session['user']);//use session id
foreach($dateList as $value){//get each value
echo '<tr>' .$value.'</tr>';}
}
?>
<body>
<table>
<th><tr> Made Budgets</tr> </th>
<?php DispMonth(); ?>
</body>
</html>
我的 GetDates 函数是:
function GetDates($id){
$result=mysql_query('select monthYear from database where userId='.$_Session['user'].'');
while ($row=mysql_fetch_object($result)){
$x[]=$row['monthYear'];}
return x;
}
基本上我希望表格看起来像这样:
|monthYear| edit | delete |
编辑和删除是链接/按钮,它将把monthYear的值发送到一个新的php页面以获取所有值。(Monthyear是我的sql表中的主键)
最佳答案
您的代码存在一些需要修复的问题,并且需要进行一些更改才能使其正常工作,例如:
您的表结构错误。
<tr>
不能在里面<th>
,也是结束</table>
标签丢失。您正在使用
mysql_fetch_object()
从结果集中获取行函数,但使用$row[...]
访问列值,这是错误的。使用mysql_fetch_array()
相反。while ($row=mysql_fetch_array($result)){ ...
鉴于
monthYear
是表的主键,请在foreach
中的 edit 和 delele 按钮中使用此列值循环,像这样:<a href="newPage.php?monthYear=<?php echo $value ?>&edit">edit</a> <a href="newPage.php?monthYear=<?php echo $value ?>&delete">delete</a>
稍后,在 newPage.php 页面上,您可以编辑或删除任何特定行,如下所示:
if(isset($_GET['edit'])){ $monthYear = $_GET['monthYear']; // Edit the row } if(isset($_GET['delete'])){ $monthYear = $_GET['monthYear']; // Delete the row }
所以你的函数和表结构将是这样的:
<table>
<tr>
<th>Made Budgets</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php DispMonth(); ?>
</table>
function DispMonth(){
$dateList=GetDates($_Session['user']);
foreach($dateList as $value){
?>
<tr>
<td><?php echo $value; ?></td>
<td><a href="newPage.php?monthYear=<?php echo $value ?>&edit">edit</a></td>
<td><a href="newPage.php?monthYear=<?php echo $value ?>&delete">delete</a></td>
</tr>
<?php
}
}
function GetDates($id){
$result=mysql_query('select monthYear from database where userId='.$_SESSION['user'].'');
$x = array();
while ($row=mysql_fetch_array($result)){
$x[] = $row['monthYear'];
}
return x;
}
<小时/>
旁注:不要使用mysql_*
函数,它们从 PHP 5.5 开始被弃用,并在 PHP 7.0 中被完全删除。使用 mysqli
或 pdo
反而。 And this is why you shouldn't use mysql_*
functions 。
关于php - 将未知数量的字符串转换为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41913736/