简体   繁体   English

从db中检索数据并将其显示在php中的表中..看到这段代码有什么问题吗?

[英]retrieve data from db and display it in table in php .. see this code whats wrong with it?

  $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>";
    }
?>

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. 这就是SQL注入攻击(甚至是通过SQL传递的非故意错误)的方式。 Don't do it! 不要这样做!

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. 大多数PHP函数都足够好,可以在错误条件下返回它们。 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. 您可以随时检查这些条件 - 永远不要认为PHP会按照您的期望,您的期望以及您期望的顺序执行。 This is how accident happen... 这就是事故发生的原因......

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. 祝好运。

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. 这是一段非常基本的代码,但如果您不习惯使用函数,它会有所帮助。

Here is the solution total html with php and database connections 这是解决方案总PHP与PHP和数据库连接

   <!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>

在你的while语句只需更换mysql_fetch_rowmysql_fetch_arraymysql_fetch_assoc ...取其作品...

<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>

When you are connecting database you are not passing your connection variable. 连接数据库时,您没有传递连接变量。 That is the error 那是错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM