MySQL fetch array adds duplicate values?

后端 未结 3 1648
无人共我
无人共我 2021-01-18 12:59

I am getting this:

Array
(
[0] => 1
[id] => 1
[1] => 778613c4344dbc9565c359c1154c6a18
[session] => 778613c4344dbc9565c359c1154c6a18
[2] => fn
         


        
3条回答
  •  再見小時候
    2021-01-18 13:55

    If you don't specify a result type as a second parameter, mysql_fetch_array() will default to MYSQL_BOTH (quoting) :

    By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.


    If this is not what you want, you have to pass a second parameter to that function, to indicate what type of results you want.

    For example, to only get an associative array with columns names as keys :

    $result = mysql_query("SELECT session FROM users WHERE username='$cookie[username]' AND first_name='$cookie[first_name]' AND last_name='$cookie[last_name]' AND campus='$cookie[campus]' AND id='$cookie[id]'");
    $user = mysql_fetch_array($result, MYSQL_ASSOC);
    


    As a sidenote :

    • Make sure you are escaping the variables you inject into your query, to prevent SQL Injections, using, for example, mysql_real_escape_string()
    • Before using mysql_fetch_array(), you should test if mysql_query() was successful,
    • And, especially for a new project, you should use mysqli or PDO, and not the old mysql_* functions -- see Choosing an API.

提交回复
热议问题