Reputation:
I am attempting to retrieve the names of different columns of a MYSQL table and then save them as individual string variables from which I set as cookies. The problem is that all of the recipes are saved in a single element in an array. It would even be helpful if I could save each field as a separate object in an array. Moreover, some of the field names may contain blank characters (e.g. spaces). I honestly am not too sure how to approach this, however I have attempted in my simplified code below:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "db_name";
$table_id = "table_name";
$conn = mysqli_connect($servername, $username, $password, $db_public_tables);
if (!$conn) {
die("Error: " . mysqli_connect_error());
}
$sql = "SHOW COLUMNS FROM `$table_id`";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
$field_array = implode(" ", $row[0]);
setcookie('selected_field_array_cookie', $field_array);
}
mysqli_close($conn);
?>
I am looking for an output where I am able to print a specific field name on a html page. For example:
echo $field3;
Thanks for your consideration. Answers in any form are welcome although preferably using PHP/MYSQL/JS
Upvotes: 1
Views: 54
Reputation: 1702
I assume this is what you're looking for:
$servername = "localhost";
$username = "root";
$password = "";
$database = "db_name";
$table_id = "table_name";
$conn = mysqli_connect($servername, $username, $password, $database);
if(!$conn) {
die("Error: " . mysqli_connect_error());
}
$sql = "SHOW COLUMNS FROM `$table_id`";
$result = mysqli_query($conn, $sql);
$field_array = array();
$index = 1;
$omitted_fields = array('id', 'reg_date');
while($row = mysqli_fetch_array($result)){
if(!in_array($row[0], $omitted_fields)) {
$field_array['field' . $index] = $row[0];
setcookie('field' . $index, $row[0]);
extract($field_array);
$index += 1;
}
}
echo $field1 . "<br>";
echo $field2 . "<br>";
echo $field3 . "<br>";
echo $_COOKIE['field1'] . "<br>";
echo $_COOKIE['field2'] . "<br>";
echo $_COOKIE['field3'] . "<br>";
mysqli_close($conn);
Hope it works.
Upvotes: 1