dpm91915 2015-03-18 09:19
浏览 44
已采纳

PHP:MySQL选择查询与字符串操作

I have a database and a string with about 100,000 key / value-pair records and I want to create a function to find the value.

Is it better to use a string or a database, considering performance (page load time) and crash safety? Here are my two code examples:

1.

echo find("Mohammad");

function find($value){
    $sql = mysql_query("SELECT * FROM `table` WHERE `name`='$value' LIMIT 1");
    $count = mysql_num_rows($sql);
    if($count > 0){
        $row = mysql_fetch_array($sql);
        return $row["family"];
    } else {
        return 'NULL';
    }
}

2.

$string = "Ali:Golam,Mohammad:Offer,Reza:Now,Saber:Yes";

echo find($string,"Mohammad");

function find($string,$value){
    $array = explode(",",$string);
    foreach($array as $into) {
        $new = explode(":",$into);
        if($new[0] == $value) {
            return $new[1];
            break;
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dougao7801 2015-03-18 09:22
    关注

    The database is pretty sure a good idea.

    1. Databases are fast, maybe they are not as fast as basic String operations in PHP, but if there is a lot of data, databases will probably be faster. A basic select Query takes (on my current default Desktop Hardware) about 15ms, cached less than 1ms, and this is pretty much independend of the number of names in your table, if the indexes are correct. So your site will always be fast.

    2. Databases won't cause a StackOverflow or an out of memory error and crash your site (this is very depending on your PHP-Settings and Hardware)

    3. Databases are more flexible, imagine you want to add / remove / edit names after creating the first Data-Set. It's very simple with "INSERT INTO", "DELETE FROM" and "UPDATE" to modify the data, better than editing a string somewhere in your code with about 100.000 entries.

    Your Code

    1. You definitly need to use MySQLi or PDO instead, code maybe like this:
    $mysqli = new mysqli("host", "username", "password", "dbname");
    $stmt = $mysqli->prepare(
        'SELECT string FROM table WHERE name = ? LIMIT 1'
    );
    $stmt->bind_param("s", $value);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($string);
    $stmt->fetch();
    $stmt->close();
    

    This uses MySQLi and Prepared Statements (for security), instead of the depracated MySQL extension (in PHP 5.5)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助