使用变量获取数据库

时间:2017-05-22 08:55:48

标签: php mysql

我正在尝试使用变量拉取数据库。

$username = $_SESSION['user_username'];
$req = mysql_query("select id, username, message from '$username'_inbox");
while($dnn = mysql_fetch_array($req))

或者这个..

$username = $_SESSION['user_username'];
$req = mysql_query("select id, username, message from '$username'");
while($dnn = mysql_fetch_array($req))

我只需要一个解决方案来获取相关的数据库用户。

1 个答案:

答案 0 :(得分:0)

  

不推荐使用mysql_ *尝试使用mysqli_ *

1)Mysql查询应该是

从table_name中选择ID,用户名和消息,其中username =' potato'

2)在查询中使用用户数据时,请使用预准备语句或PDO。避免sql注入。

       $servername = "localhost";  //host name

        $username = "username"; //username

        $password = "password"; //password

        $mysql_database = "dbname"; //database name

    //mysqli prepared statement 

        $conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());

       mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");


    $stmt = $conn->prepare("select id, username, message from table_name where username=?");

        $stmt->bind_param('s',$username);

        //The argument may be one of four types:

        //i - integer
        //d - double
        //s - string
        //b - BLOB
        //change it by respectively 

        $stmt->execute();

        $result= $stmt->get_result();
        $rows  =$result->num_rows;

        if($row>0)
        {
            while($row=$result->fetch_assoc())
            {

                print_r($row);

            }


        }
        $stmt->close();
         $conn->close();