From MySQL to array

Hi guys, so basically im selectin a row called ‘job’ which could have different numbers from 0 to 6. And im just trying to put this into an array something like this.

$plec = array(
		'0' => 'sm1',
		'1' => 'sm2',
		'2' => 'sm3',
		'3' => 'sm3',
		'4' => 'sm4',
		'5' => 'sm5',
		'6' => 'sm6',

		);

$sql1 = $player->prepare('SELECT id, name, job, level FROM player WHERE account_id = ?');
$sql1->bind_param('i', $_SESSION['id']);
$sql1->execute();
$result = $sql1->get_result();
$charCount = $result->num_rows;	
if($charCount == 0) {
	echo 'n/a';
}else {
	echo $plec[0];
	while($row = $result->fetch_assoc()) {			
		echo '<td>Something</td>';
		echo '<td>'.$row['id'].'</td>';
		echo '<td>'.$row['name'].'</td>';
	}
}

So now the output is going to be

echo $plec[0];
output:
sm1

So how i get the query to automatically collab with the array? So the array can output whatever will the query spill out.

This sounds like you’re storing a job id in the database, and want to print out the job title from a PHP array. If this is the case, you want something like:

echo '<td>'.$row['id'].'</td>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$plec[$row['job']].'</td>';

The third line is the new one. You are saying "get me the value in $plec whose key is the value of $row['job']".

As an aside, you might want to consider storing your job types in the database as well, it usually makes for more a flexible program to have your data separate from the code.

1 Like

What is the purpose of the array to begin with?

You can use the array keys, so if the output from the query is 1 for instance, it would use the value at position 1 in the array, but if this stuff is coming from the database anyway, just have those values live there as well.

Sponsor our Newsletter | Privacy Policy | Terms of Service