Here is my code to retrive value from database
$query = "SELECT * FROM t_contact
WHERE id = {$project_details_id} LIMIT 1";
$all_post_info1 = mysql_query($query, $connection);
confirm_query($all_post_info1);
$project_details = mysql_fetch_array(show_project_details($project_details_id));
foreach ($project_details as $fieldname) {
echo $fieldname . "</br>";
}
And
function confirm_query($confirm_result) {
if (!$confirm_result) {
die("Database query failed1: " . mysql_error());
}
}
And i get output twice for each field. There are 27 column in my database and i get 54 output. For example, there are name, email column in database and my output shows like
name
name
email
email
Some please tell me what is wrong with this code.
By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
That's because your $project_details
actually looks [something] like this:
$project_details = array(
[0] => 'name',
[name] => 'name',
[1] => 'email',
[email] => 'email'
);
Try specifying MYSQL_ASSOC
in your mysql_fetch_array
call.
Instead of using foreach you should use while. As ex:
while($row = db_fetch_array($all_post_info1)) {
echo $row[field_name];
}
Hope it will help you.
The mysql_fetch_array()
by default returns keys in both indexed and associated format.
Use the MYSQL_ASSOC
parameter to get only the associative version:
$project_details = mysql_fetch_array(show_project_details($project_details_id), MYSQL_ASSOC);
As is customary, I'll also remind you that mysql functions are deprecated and you should consider using e.g. PDO.
Change this line:
$project_details = mysql_fetch_array($project_details_id);
With this line:
$project_details = mysql_fetch_array($project_details_id, MYSQL_ASSOC);
Try doing this instead:
$query = "SELECT * FROM t_contact
WHERE id = {$project_details_id} LIMIT 1";
$all_post_info1 = mysql_query($query, $connection);
confirm_query($all_post_info1);
while($data = mysql_fetch_assoc($all_post_info1))
{
print_r($data);
}
mysql_fetch_assoc will return an associative array, which means an array where the keys are associated with the fields in your query. mysql_fetch_array will return an array with the fields as well as numeric key values, hence the double variables. I rarely ever use mysql_fetch_array, in almost every case mysql_fetch_assoc is the way to go.