从 db 中检索数据并将其显示在 php 的表中.. 看到这段代码有什么问题吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4331353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
retrieve data from db and display it in table in php .. see this code whats wrong with it?
提问by noddychan
$db = mysql_connect("localhost", "root", "");
$er = mysql_select_db("ram");
$query = "insert into names values('$name','$add1','$add2','$mail')";
$result = mysql_query($query);
print "<p> Person's Information Inserted </p>";
$result = mysql_query("SELECT * FROM names");
?>
<table border="2">
<tr>
<th>Name</th>
<th>Address Line 1</th>
<th>Address Line 2 </th>
<th>E-mail Id </th>
</tr>
<?
while ($array = mysql_fetch_row($result));
{
print "<tr> <td>";
echo $array[0];
print "</td> <td>";
echo $array[1];
print "</td> <td>";
echo $array[2];
print "</td> <td>";
echo $array[3];
print "</td> </tr>";
}
?>
采纳答案by Luke Stevenson
Try this:
尝试这个:
<?php
# Init the MySQL Connection
if( !( $db = mysql_connect( 'localhost' , 'root' , '' ) ) )
die( 'Failed to connect to MySQL Database Server - #'.mysql_errno().': '.mysql_error();
if( !mysql_select_db( 'ram' ) )
die( 'Connected to Server, but Failed to Connect to Database - #'.mysql_errno().': '.mysql_error();
# Prepare the INSERT Query
$insertTPL = 'INSERT INTO `name` VALUES( "%s" , "%s" , "%s" , "%s" )';
$insertSQL = sprintf( $insertTPL ,
mysql_real_escape_string( $name ) ,
mysql_real_escape_string( $add1 ) ,
mysql_real_escape_string( $add2 ) ,
mysql_real_escape_string( $mail ) );
# Execute the INSERT Query
if( !( $insertRes = mysql_query( $insertSQL ) ) ){
echo '<p>Insert of Row into Database Failed - #'.mysql_errno().': '.mysql_error().'</p>';
}else{
echo '<p>Person\'s Information Inserted</p>'
}
# Prepare the SELECT Query
$selectSQL = 'SELECT * FROM `names`';
# Execute the SELECT Query
if( !( $selectRes = mysql_query( $selectSQL ) ) ){
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}else{
?>
<table border="2">
<thead>
<tr>
<th>Name</th>
<th>Address Line 1</th>
<th>Address Line 2</th>
<th>Email Id</th>
</tr>
</thead>
<tbody>
<?php
if( mysql_num_rows( $selectRes )==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysql_fetch_assoc( $selectRes ) ){
echo "<tr><td>{$row['name']}</td><td>{$row['addr1']}</td><td>{$row['addr2']}</td><td>{$row['mail']}</td></tr>\n";
}
}
?>
</tbody>
</table>
<?php
}
?>
Notes, Cautions and Caveats
注意事项、注意事项和注意事项
Your initial solution did not show any obvious santisation of the values before passing them into the Database. This is how SQL Injection attacks (or even un-intentional errors being passed through SQL) occur. Don't do it!
在将值传递到数据库之前,您的初始解决方案没有显示任何明显的值清理。这就是 SQL 注入攻击(甚至是通过 SQL 传递的非故意错误)发生的方式。不要这样做!
Your database does not seem to have a Primary Key. Whilst these are not, technically, necessary in all usage, they are a good practice, and make for a much more reliable way of referring to a specific row in a table, whether for adding related tables, or for making changes within that table.
您的数据库似乎没有主键。虽然从技术上讲,这些在所有用法中都不是必需的,但它们是一种很好的做法,并且可以提供一种更可靠的方式来引用表中的特定行,无论是添加相关表还是在该表中进行更改。
You need to check every action, at every stage, for errors. Most PHP functions are nice enough to have a response they will return under an error condition. It is your job to check for those conditions as you go - never assume that PHP will do what you expect, how you expect, and in the order you expect. This is how accident happen...
您需要在每个阶段检查每个操作是否有错误。大多数 PHP 函数都足够好,可以在错误条件下返回响应。您的工作是在执行过程中检查这些条件 - 永远不要假设 PHP 会按照您的期望、如何期望以及按照您期望的顺序执行。事故是这样发生的……
My provided code above contains alot of points where, if an error has occured, a message will be returned. Try it, see if any error messages are reported, look at the Error Message, and, if applicable, the Error Code returned and do some research.
我上面提供的代码包含很多点,如果发生错误,将返回一条消息。尝试一下,看看是否报告了任何错误消息,查看错误消息,如果适用,返回错误代码并进行一些研究。
Good luck.
祝你好运。
回答by Leah
This is a very simple code I use and you manipulate it to change the colour and size of the table as you see fit.
这是我使用的一个非常简单的代码,您可以操作它来更改您认为合适的表格的颜色和大小。
First connect to the database:
首先连接数据库:
<?php
$connect=mysql_connect('localhost', 'root', 'password');
mysql_select_db("name");
//here u select the data you want to retrieve from the db
$query="select * from tablename";
$result= mysql_query($query);
//here you check to see if any data has been found and you define the width of the table
If($result){
echo "<table width ='340' align='left'>
<tr color ='#5D9951>";
$i=0;
If(mysql_num_rows($result)>0)
{
//here you fetch the data from the database and print it in the respective columns
while($i<mysql_num_fields($result))
{
echo "<th>".mysql_field_name($result, $i)."</th>";
$i++;
}
echo "</tr>";
$color=1;
while($rows=mysql_fetch_array($result, MYSQL_ASSOC))
{
If ($color==1){
echo "<tr color='#'#cccccc'>";
foreach ($rows as $data){
echo "<td align='center'>".$data. "</td>";
}
$color=2;
}
$color=1;
}
} else {
echo"no results found";
echo "</table>";
} else {
echo "error running query:".MYSQL_error();
}
?>
It's a very elementary piece of code but it helps if you are not used to using functions.
这是一段非常基本的代码,但如果您不习惯使用函数,它会有所帮助。
回答by Satyabrata sahoo
Here is the solution total html with php and database connections
这是带有php和数据库连接的解决方案总html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>database connections</title>
</head>
<body>
<?php
$username = "database-username";
$password = "database-password";
$host = "localhost";
$connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysql_select_db("test_db", $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM table_one ");
?>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>Employee_id</th>
<th>Employee_Name</th>
<th>Employee_dob</th>
<th>Employee_Adress</th>
<th>Employee_dept</th>
<td>Employee_salary</td>
</tr>
</thead>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $result ) ){
echo
"<tr>
<td>{$row\['employee_id'\]}</td>
<td>{$row\['employee_name'\]}</td>
<td>{$row\['employee_dob'\]}</td>
<td>{$row\['employee_addr'\]}</td>
<td>{$row\['employee_dept'\]}</td>
<td>{$row\['employee_sal'\]}</td>
</tr>\n";
}
?>
</tbody>
</table>
<?php mysql_close($connector); ?>
</body>
</html>
回答by Laptop Medico
In your while statement just replace mysql_fetch_row
with mysql_fetch_array
or mysql_fetch_assoc
... whichever works...
在您的 while 语句中,只需替换mysql_fetch_row
为mysql_fetch_array
或mysql_fetch_assoc
...无论哪个有效...
回答by Gopal Sharma
<html>
<head>
<meta charset="UTF-8">
<title>LoginDB</title>
</head>
<body>
<?php
$con= mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
if(!$con)
{
die('not connected');
}
$con= mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
?>
<div>
<td>Login Page Database</td>
<table border="1">
<th> First Name</th>
<th>Last Name</th>
<th>UserName</th>
<th>Password</th>
<th>Gender</th>
<th>D.O.B.</th>
<th>Phone Number</th>
<th>Address</th>
</tr>
<?php
while($row= mysqli_fetch_array($con))
<!-- Fetch each row from signup Table -->
{
?>
<tr>
<td><?php echo $row['FirstName']; ?></td>
<td><?php echo $row['LastName']; ?></td>
<td><?php echo $row['Username']; ?></td>
<td><?php echo $row['Password'] ;?></td>
<td><?php echo $row['Gender'] ;?></td>
<td><?php echo $row['DOB'] ;?></td>
<td><?php echo $row['PhoneNumber'] ;?></td>
<td><?php echo $row['Address'] ;?></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>