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