如何在html输入文本中显示mysql数据?

时间:2017-12-12 10:42:02

标签: php html mysql

我创建了带生成文本的html文件,我想从mysql数据库中填充名称和日期等字段。问题是我试图在html输入文本标签中显示来自mysql的数据。但它只显示字母S. 这是我的PHP代码:

    <?php



    $db_host = ''; // Server Name
    $db_user = ''; // Username
    $db_pass = ''; // Password
    $db_name = ''; // Database Name

    $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

    if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = "SELECT ime_prezime,datumpocetka,datumzavrsetka,broj_dana,sektor,
mesto,tip,obrazlozenje,vreme_slanja
FROM godisnji
WHERE id=74";
mysqli_close($con);
?>

这是我的HTML代码的一部分:

<p style="text-align:justify">1. Zaposlenom <input  name="lname" type="text" value="<?php  echo $result['ime_prezime'];?>"/>
na poslovima $posao, se odobrava
korišćenje godišnjeg odmora za 2018. godinu, u trajanju od 20 radnih dana.</p>

2 个答案:

答案 0 :(得分:0)

只是因为......

现在这是非常基础的,您应该学习使用PDO或至少使用mysqli类。但是现在......

这是一个小的演示代码......(它可能有错误,因为我没有运行它)

<?php
// The Database Connection Stuff should be in it's own file
// and included in each file that requires a database connection.
$db_host = ''; // Server Name
$db_user = ''; // Username
$db_pass = ''; // Password
$db_name = ''; // Database Name
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


// Create the SQL
$sql = "SELECT ime_prezime,datumpocetka,datumzavrsetka,broj_dana,sektor,
mesto,tip,obrazlozenje,vreme_slanja
FROM godisnji
WHERE id=74";

// Run the SQL statement
$query = mysqli_query($con,$sql);
// Read back the ROW as an associative array
$result = mysqli_fetch_assoc($query);

// DEBUG to learn what you get  back and CHECK it's what you expect!
var_dump($result);
// If it exists...
echo ($result['ime_prezime']);

mysqli_close($con);

// Then Read up on how to use PDO or mysqli Class

作为一个建议,由于你不会总是有一个有效的价值,你可以用而不是......

<?php  echo $result['ime_prezime'];?>

试试这个

<?= isset($result['ime_prezime'])?$result['ime_prezime']:'';?>

以上测试$ result [&#39; ime_prezime&#39;]是否存在,如果存在,则会打印出来,否则会打印出来&#39;

在PHP&#34;

中查找&#34;三元运算符

答案 1 :(得分:0)

<?php

$db_host = ''; // Server Name
$db_user = ''; // Username
$db_pass = ''; // Password
$db_name = ''; // Database Name

// Create connection
$conn = new mysqli($db_host, $db_user , $db_pass , $db_name );


if ($conn->connect_error)
{
echo "Failed to connect to MySQL: " . $conn->connect_error;
}

$result = "SELECT ime_prezime,datumpocetka,datumzavrsetka,broj_dana,sektor,
           mesto,tip,obrazlozenje,vreme_slanja FROM godisnji WHERE id=74";

$sqlQuery = $conn->query($result);

$value = $sqlQuery->fetch_assoc()['ime_prezime'];



echo "<p style='text-align:justify'>1. Zaposlenom <input 
        name='lname'type='text' value='".$value."'/></p>";

$conn->close();

?>