Simple way to read single record from MySQL

后端 未结 20 1120
一整个雨季
一整个雨季 2020-11-30 23:46

What\'s the best way with PHP to read a single record from a MySQL database? E.g.:

SELECT id FROM games

I was trying to find an answer in t

相关标签:
20条回答
  • 2020-12-01 00:36
    $id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
    
    0 讨论(0)
  • 2020-12-01 00:38

    The easiest way is to use mysql_result. I copied some of the code below from other answers to save time.

    $link = mysql_connect('localhost','root','yourPassword')
    mysql_select_db('database',$link);
    $sql = 'SELECT id FROM games'
    $result = mysql_query($sql,$link);
    
    $num_rows = mysql_num_rows($result);
    
    // i is the row number and will be 0 through $num_rows-1
    for ($i = 0; $i < $num_rows; $i++) {
        $value = mysql_result($result, i, 'id');
        echo 'Row ', i, ': ', $value, "\n";
    }
    
    0 讨论(0)
  • 2020-12-01 00:39
    function getSingleRow($table, $where_clause="", $column=" * ",$debug=0) {
        $SelectQuery = createQuery($table, $where_clause, $column);
    
        $result = executeQuery($SelectQuery,$debug);
        while($row = mysql_fetch_array($result)) {
            $row_val = $row;
        }
        return $row_val;
    }
    
    0 讨论(0)
  • 2020-12-01 00:41

    'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:

    with mysqli

    $sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
    $result = $db->query($sql);
    $row = $result->fetch_row();
    

    with Zend Framework

    //Inside the table class

    $select = $this->select()->where('user_id = ?', 1);  
    $row = $this->fetchRow($select);
    
    0 讨论(0)
  • 2020-12-01 00:41

    I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:

    $r = mysql_query('SELECT id FROM table') or die(mysql_error());
    if (mysql_num_rows($r) > 0) {
        echo mysql_result($r); // will output first ID
        echo mysql_result($r, 1); // will ouput second ID
    }
    
    0 讨论(0)
  • at first : CREATE connection

    $conn =  new mysqli('localhost', 'User DB', 'Pass DB', 'Table name');
    

    and then get the record target :

    $query = "SELECT id FROM games LIMIT 1"; // for example query
    $result = $conn->query($query); // run query
    if($result->num_rows){ //if exist something
        $ret = $result->fetch_array(MYSQLI_ASSOC); //fetch data
    }else{
        $ret = false;
    }
    var_dump($ret);
    
    0 讨论(0)
提交回复
热议问题