Pulling data from mySQL to a text document php

时间:2018-09-18 20:32:19

标签: php mysql

I'm trying to take the data I have from mySQL database and have it replace a certain string in a .txt file. I feel like I'm close but the string I want to replace is only getting replaced with a blank space.

<?php
$servername = "localhost";
$username = "rob1289";
$password = "databasetest";
$dbname = "RobertCornell2";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM name ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    //"" . $row["first"]. "<br>";
    $fname_from_db = $row["first"];
    $mname_from_db = $row["middle"];
    //echo $row["id"];
}
} else {
echo "0 results";
echo "<br/>Error: " . mysqli_error($conn);
}
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fname_from_db = $row["first"];
$mname_from_db = $row["middle"];
$placeholders = array('fin', 'min');
$namevals = array($fname_from_db);
$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);
file_put_contents($path_to_file,$file_contents);


fclose($fh); 

mysqli_close($conn);
?>

1 个答案:

答案 0 :(得分:0)

是因为myfunc = (options={}) => { const {a=true, b=true, c=true} = options; .... } (替换)有一个元素,而$namevals(搜索)有两个元素?

来自PHP doc

  

如果replace的值少于搜索的值,则将空字符串用于其余的替换值。

相关问题