Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL fetch array adds duplicate values?

Tags:

arrays

php

mysql

I am getting this:

Array
(
[0] => 1
[id] => 1
[1] => 778613c4344dbc9565c359c1154c6a18
[session] => 778613c4344dbc9565c359c1154c6a18
[2] => fn
[first_name] => fn
[3] => ln
[last_name] => ln
[4] => un
[username] => un
[5] => 016e6128e8ca9dda1b310c364d9b622c
[password] => 016e6128e8ca9dda1b310c364d9b622c
[6] => address
[email] => address
[7] => 100
[permission] => 100
[8] => 10
[year_level] => 10
[9] => 
[department] => 
[10] => Sample
[campus] => Sample
[11] => 0
[logo_url] => 0
)

After running this

$user = mysql_fetch_array(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]'")) 

Any ideas why it is duplicating like this? Thanks

EDIT: I think the primary key is doing this. Any idea on how to stop it?

like image 272
Sam Avatar asked Feb 12 '12 09:02

Sam


3 Answers

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.
like image 73
Pascal MARTIN Avatar answered Nov 14 '22 19:11

Pascal MARTIN


Try second parameter MYSQL_ASSOC or MYSQL_NUM. MYSQL_BOTH is ued by default, returning with both numberic and field keys.

like image 1
Oleg Avatar answered Nov 14 '22 18:11

Oleg


Pascal MARTIN has already explained the reason behind it.

I'll tell you to use mysql_fetch_assoc It'll give you only the associated array. Numerical part will not be present.

like image 1
Shiplu Mokaddim Avatar answered Nov 14 '22 18:11

Shiplu Mokaddim