简体   繁体   中英

For and While loop in php mysql

I have the following code. Is there any way to combine and simplify it?

The output in the json.html file should be like this: ["abc","def","ghi"] .

    <?php
    // Make a MySQL Connection
    mysql_connect("localhost", "root", "admin") or die(mysql_error());
    mysql_select_db("test1") or die(mysql_error());

    // Get all the data from the "example" table
    $result = mysql_query("SELECT * FROM test_auto_complete") or die(mysql_error());  

    $menu = array();

    while($row = mysql_fetch_assoc($result))
    {
    $menu[] = array("id" => $row['username'],);
    } 

    foreach($menu as $key=>$value)
    {
      $menu[$key] = $value['id'];
    }


    $my_json_content = json_encode($menu);

    $file = 'json.html';
    $current = file_get_contents($file);
    file_put_contents($file, $my_json_content);

    ?>

I know the code looks bad, but even so, can someone help me?

Thanks
Haan

If you want to put content in file than just use file_put_contents

$my_json_content = json_encode($menu);
$file = 'json.html';
file_put_contents($file, $my_json_content);

And use this while loop without foreach

while($row = mysql_fetch_assoc($result))
{
$menu[] = $row['username'];
} 

I won't even give you solution with mysql_* because they are depracated look at the solution in PDO

<?php 
$dsn = 'mysql:dbname=test1;host=127.0.0.1';
$user = 'root';
$password = 'admin';

try{
    $dbh = new PDO($dsn, $user, $password);
    $menu = array();
    foreach ($conn->query("SELECT * FROM test_auto_complete") as $row)
             $menu[] = $row['username'];

    file_put_contents('json.html', json_encode($menu));

}catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Tips:

  1. Mysql_* functions are depracated and they don't support a lot of features of MySQL
  2. Foreach in your case was senseless.
  3. File_get_contents() in your code does not have any sense for me, what do you need the content of file for?
  4. Variables are used for data which is going to be changed. For example in your case you use variable for json.html which seems to be constant, if so, then use constant string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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