1

How could I return the values from this query as an array so that I can perform an action with the array?

$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);

How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.

$userarray = array("user1","user2"); 
1
  • 1
    1) You need to execute the query 2) You probably want to fetch the data in a while loop Commented Apr 10, 2016 at 6:33

2 Answers 2

1

Before I point out best practices, you need working code first. So I'll give you a simple solution first.

To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:

$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
    $rows[]=$row;
}
print_r($rows);

Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.

Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.

Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.

Sign up to request clarification or add additional context in comments.

Comments

0

You would need to use a foreach loop to do it:

$userarray = [];

foreach($row as $single)
{
    array_push($userarray, $single['username']);
}

and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.

$db        = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.