duanba5777 2014-07-13 23:57
浏览 18
已采纳

连接数据库最安全的方法是什么? [关闭]

im wondering what is the best and safest way to make a connection to a database to include in all the php files where i have to get data from the database. right now i always make a connection every single time lets say i use a while to get some data from a certain table from database that looks like the code below. Can you guys tell me what is the best way to make a connection and use it for the while?

How i make a connection for the while now every single time

$id=$_SESSION['id'];
    $connect = mysql_connect("localhost", "username", "password");
    $select_data = mysql_select_db('databasename', $connect);
    $select_data = mysql_query("SELECT * FROM members WHERE `id`='$id'") or die(mysql_error());
    while($fetch=mysql_fetch_assoc($select_data)) {

        // Show profile pic.
        $oImgBox = $dom->getElementById('adminProfilePicture');
        $oImg = $dom->createElement('image');
        $oImg->setAttribute('src',$fetch["profilepic"]);
        $oImgBox->appendChild($oImg);
  • 写回答

1条回答 默认 最新

  • duanchun6148 2014-07-14 00:21
    关注

    As others have mentioned, you obviously need to use either mysqli or prepared statements. But with that aside, if I am understanding correctly, I believe what you are looking for is the include() function.

    With an include, you are able to put a particular script (such as db connection), on every page that requires it easily. See here http://php.net/manual/en/function.include.php

    The first step is putting your PHP code into a standalone php file, such as db_connect.php or in your case user_profile.php. Then, for every page you need to make a connection to the database, you would add include 'user_profile.php'; above your html.

    EDIT - Adding sample DB connection script.

    $db = new mysqli('localhost', 'user', 'pass', 'demo');
    
    if($db->connect_errno > 0){
      die('Unable to connect to database [' . $db->connect_error . ']');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像