What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

前端 未结 10 697
别跟我提以往
别跟我提以往 2021-01-17 06:18

I want to fetch data from a mysql table using php. Please, can anyone tell me what is wrong with this code? What is the correct code to fetch data from a mysql database:

相关标签:
10条回答
  • 2021-01-17 06:55

    Change the "WHILE" to "while". Because php is case sensitive like c/c++.

    0 讨论(0)
  • 2021-01-17 06:56

    use this code

      while ($rows = mysql_fetch_array($query)):
    
       $name = $rows['Name'];
       $address = $rows['Address'];
       $email = $rows['Email'];
       $subject = $rows['Subject'];
       $comment = $rows['Comment'];
    
       echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";
    
       endwhile;
    
       ?>
    
    0 讨论(0)
  • 2021-01-17 06:57

    Try this

    <?php
    // 1. Enter Database details
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = 'password';
    $dbname = 'database name';
    
    // 2. Create a database connection
    $connection = mysql_connect($dbhost,$dbuser,$dbpass);
    if (!$connection) {
        die("Database connection failed: " . mysql_error());
    }
    
    // 3. Select a database to use 
    $db_select = mysql_select_db($dbname,$connection);
    if (!$db_select) {
        die("Database selection failed: " . mysql_error());
    }
    
    $query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ");
    
    while ($rows = mysql_fetch_array($query)) { 
       $name = $rows['Name'];
       $address = $rows['Address'];
       $email = $rows['Email'];
       $subject = $rows['Subject'];
       $comment = $rows['Comment']
    
       echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";      
    } 
    
    ?>
    

    Not tested!! *UPDATED!!

    0 讨论(0)
  • 2021-01-17 06:59

    If this is the code you have, then you will get an error because, you are reassigning $row while in the loop, so you would never be able to iterate over the results. Replace

    $rows = $rows['Name'];
    

    with

    $name = $rows['Name']'
    

    So your code would look like

    WHILE ($rows = mysql_fetch_array($query)):
    
       $name = $rows['Name'];
       $address = $rows['Address'];
       $email = $rows['Email'];
       $subject = $rows['Subject'];
       $comment = $rows['Comment'];
    

    Also I am assuming that the column names in the table users are Name, Address, Email etc. and not name,address, email. Remember that every variable name/field nameh is case sensitive.

    0 讨论(0)
提交回复
热议问题