在div php javascript中从mysql显示获取所有数据
你好,我的问题很简单,我有一个表新闻,我有一个按钮bt1,和一个显示结果的div,我想显示表中的所有行,当我单击按钮时,我只得到第一行,我如何显示所有结果在div php javascript中从mysql显示获取所有数据,javascript,php,mysql,Javascript,Php,Mysql,你好,我的问题很简单,我有一个表新闻,我有一个按钮bt1,和一个显示结果的div,我想显示表中的所有行,当我单击按钮时,我只得到第一行,我如何显示所有结果 <script> function shownews(id) { <? php include('db.php'); $query = mysql_query("SELECT * FROM news"); while ($row = mysql_fetch_array($query)) {
<script>
function shownews(id) { <? php
include('db.php');
$query = mysql_query("SELECT * FROM news");
while ($row = mysql_fetch_array($query)) {
$a = $row['news_title'];
} ?>
var ab = <? php echo json_encode($a); ?> ;
id.innerHTML = ab;
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>
函数shownews(id){
var ab=;
id.innerHTML=ab;
}
看新闻
您正在覆盖$a,因此只会得到最后一行
改变
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
}
到
编辑:Royal_bg正确-额外信息:
注意:如果使用array_push()将一个元素添加到数组中,最好使用$array[]=因为这样就不会有调用函数的开销
在写任何东西之前,你一直在执行。写下答案后,尝试更改结束括号
<script>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
?>
var ab = <?php echo $a; ?>;
id.innerHTML += ab;
<?php
}
?>
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>
功能shownews(id){
var ab=;
id.innerHTML+=ab;
}
看新闻
试试看
$a = array();
while ($row = mysql_fetch_array($query)) {
$a[] = $row['news_title'];
} ?>
// print array
print_r($a);
您的echo json_编码($a);不在while循环中,因此只能渲染一行。
另外,如果我了解您在做什么,您希望只有在触发按钮单击时才执行PHP吗?这不是做这件事的方式。。。php是一种服务器语言,其中javascript仅由浏览器执行
我没有
试试这个:
功能shownews(id){
document.getElementById(id).innerHTML=document.getElementById('news').innerHTML;
}
看新闻
功能显示新闻(id){
id.innerHTML=;
}
您应该使用mysqli,mysql已被弃用。$a=array()
实际上是不必要的-…创建新数组时的$var[]行为。()两件事:json_编码是不必要的,因为$a只是一个字符串。这并不能解决问题,因为id.innerHTML=ab
无论如何都会覆盖div中的内容。
$a = array();
while ($row = mysql_fetch_array($query)) {
$a[] = $row['news_title'];
} ?>
// print array
print_r($a);
<script type="text/javascript">
function shownews(id) {
document.getElementById(id).innerHTML = document.getElementById('news').innerHTML ;
}
</script>
<div id="news" style="display:none ;">
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
echo $row['news_title'] . '<br />' ;
}
?>
</div>
<div id="results"></div>
<button id="btn1" onclick="shownews('results')">See news</button>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a[]=$row['news_title'];
}
?>
id.innerHTML=<?php echo json_encode($a); ?>;
}