Member 13978379 Ответов: 1

Как использовать extract($row) в mysqli_fetch_array


Я хочу извлечь свои данные под user_personal.php но я не могу...

Вот мои коды

Register.php

<?php
session_start();
include 'db.inc.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}    
$hobbies_list = array('Computers', 'Dancing', 'Exercise', 'Flying',
'Golfing',
'Hunting', 'Internet', 'Reading', 'Traveling', 'Other than listed');
// filter incoming values
$username = (isset($_POST['username'])) ? trim($_POST['username']) : '';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$first_name = (isset($_POST['first_name'])) ? trim($_POST['first_name']) : '';
$last_name = (isset($_POST['last_name'])) ? trim($_POST['last_name']) : '';
$email = (isset($_POST['email'])) ? trim($_POST['email']) : '';
$city = (isset($_POST['city'])) ? trim($_POST['city']) : '';
$state = (isset($_POST['state'])) ? trim($_POST['state']) : '';
$hobbies = (isset($_POST['hobbies']) && is_array($_POST['hobbies'])) ?
$_POST['hobbies'] : array();
if (isset($_POST['submit']) && $_POST['submit'] == 'Register') {
$errors = array();
// make sure manditory fields have been entered
if (empty($username)) {
$errors[] = 'Username cannot be blank.';
}
// check if username already is registered
$sql = 'SELECT username FROM site_user WHERE username = "' .
$username . '"';
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows ($result)> 0) {
$errors[] = 'Username ' . $username . 'is already registered.';
$username = '';
}
mysqli_free_result($result);
if (empty($password)) {
$errors[] = 'Password cannot be blank.';
}
if (empty($first_name)) {
$errors[] = 'First name cannot be blank.';
}
if (empty($last_name)) {
$errors[] = 'Last name cannot be blank.';
}
if (empty($email)) {
$errors[] = 'Email address cannot be blank.';
}
if (count($errors) > 0) {
echo '<p>  Unable to process your '.
'registration.  </p> ';
echo '<p> Please fix the following: </p> ';
echo '<ul>';
foreach ($errors as $error) {
echo '<li>' . $error . '</li> ';
}
echo ' </ul> ';
} else {
// No errors so enter the information into the database.
$query = 'INSERT INTO site_user
(user_id, username, password)
VALUES
(NULL, "'. mysqli_real_escape_string($conn, $username) . '", ' .
'PASSWORD("' . mysqli_real_escape_string($conn,$password) . '"))';
$result = mysqli_query($conn,$sql);
$user_id = mysqli_insert_id($conn);
$sql = 'INSERT INTO site_user_info
(user_id, first_name, last_name, email, city, state, hobbies)
VALUES
(' . $user_id . ', '. 
'"' . mysqli_real_escape_string($conn,$first_name) . '", ' .
'"' . mysqli_real_escape_string($conn,$last_name) . '", ' .
'"' . mysqli_real_escape_string($conn,$email) . '", ' .
'"' . mysqli_real_escape_string($conn,$city) . '", ' .
'"' . mysqli_real_escape_string($conn,$state) . '", ' .
'"' . mysqli_real_escape_string($conn,join(', ', $hobbies)) . '")';

if (mysqli_query($conn,$sql));

$result = mysqli_query($conn,$sql);
$_SESSION['logged'] = 1;
$_SESSION['username'] = $username;
header('Refresh: 5; URL=main.php');
?>
<html>
<head>
<title> Register</title>
</head>
<body>
<p>  Thank you <?php echo $username; ?> for registering!  </p>
<p> Your registration is complete! You are being sent to the page you
requested. If your browser doesn't redirect properly after 5 seconds,
<a href="main.php"> click here </a> . </p>
</body>
</html>
<?php
die();
}
}
?>
<html>
<head>
<title> Register </title>
<style type="text/css">
td { vertical-align: top; }
</style>
</head>
<body>
<form action="register.php" method="post">
<table>
<tr>
<td> <label for="username"> Username: </label> </td>
<td> <input type="text" name="username" id="username" size="20" maxlength="20" value= "<?php echo $username; ?>"/> </td>
</tr> <tr>
<td> <label for="password"> Password: </label> </td>
<td> <input type= "password" name= "password" id= "password" size="20" maxlength="20" value= "<?php echo $password;?>"/> </td>
</tr> <tr>
<td> <label for="email"> Email: </label> </td>
<td> <input type="text" name= "email" id= "email" size= "20" maxlength="50" value= "<?php echo $email;?>"/> </td>
</tr> <tr>
<td> <label for="first_name"> First name: </label> </td>
<td> <input type="text" name="first_name" id="first_name" size="20" maxlength="20" value= "<?php echo $first_name;?>"/> </td>
</tr> <tr>
<td> <label for="last_name"> Last name: </label> </td>
<td> <input type="text" name="last_name" id="last_name" size="20" maxlength="20" value= "<?php echo $last_name;?>"/> </td>
</tr > <tr>
<td> <label for="city"> City: </label> </td>
<td> <input type="text" name="city" id="city" size="20" maxlength="20" value= "<?php echo $city;?>"/></td>
</tr> <tr>
<td> <label for="state"> State: </label> </td>
<td> <input type="text" name="state" id="state" size="2" maxlength="2" value= "<?php echo $state;?>"/> </td>
</tr> <tr>
<td> <label for="hobbies"> Hobbies/Interests: </label> </td>
<td> <select name="hobbies[]" id="hobbies" multiple="multiple">
<?php
foreach ($hobbies_list as $hobby)
{
if (in_array($hobby, $hobbies)) {
echo '<option value="' . $hobby . '"selected="selected">'. $hobby .
'</option> ';
} else {
echo '<option value="' . $hobby . '"> ' . $hobby . '</option> ';
}
}
?>
</select> </td>
</tr> <tr>
<td> </td>
<td> <input type="submit" name="submit" value= "Register"/> </td>
</tr>
</table>
</form>
</body>
</html>




И для моего register.php

User_personal.php

<?php
include 'auth.inc.php';
include 'db.inc.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}    
?>
<html>
<head>
<title> Personal Info </title>
</head>
<body>
<h1> Welcome to your personal information area. </h1>
<p> Here you can update your personal information, or delete your
account. </p>
<p> Your information as you currently have it is shown below. </p>
<p> <a href="main.php"> Click here </a> to return to the home page. </p>
<?php
$sql = 'SELECT
username, first_name, last_name, city, state, email, hobbies
FROM
site_user u JOIN
site_user_info i ON u.user_id = i.user_id
WHERE
username = "' . mysqli_real_escape_string($conn,$_SESSION ['username']) . '"';
<pre>User_personal.php

<?php
include 'auth.inc.php';
include 'db.inc.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}    
?>
<html>
<head>
<title> Personal Info </title>
</head>
<body>
<h1> Welcome to your personal information area. </h1>
<p> Here you can update your personal information, or delete your
account. </p>
<p> Your information as you currently have it is shown below. </p>
<p> <a href="main.php"> Click here </a> to return to the home page. </p>
<?php
$sql = 'SELECT
username, first_name, last_name, city, state, email, hobbies
FROM
site_user u JOIN
site_user_info i ON u.user_id = i.user_id
WHERE
username = "' . mysqli_real_escape_string($conn,$_SESSION ['username']) . '"';

$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
extract((array)$row);
mysqli_free_result($result);
mysqli_close($conn);
?>
<ul>
<li> First Name: <?php echo $first_name;?> </li>
<li> Last Name: <?php echo $last_name; ?> </li>
<li> City: <?php echo $city; ?> </li>
<li> State: <?php echo $state; ?> </li>
<li> Email: <?php echo $email; ?> </li>
<li> Hobbies/Interests: <?php echo $hobbies; ?> </li>
</ul>


<p> <a href="update_account.php"> Update Account </a> |
<a href="delete_account.php"> Delete Account </a> </p>
</body>
</html>


  • Имя: <?php echo $first_name;?>
  • Фамилия: <?php echo $last_name; ?>
  • Город: <?php echo $city; ?>
  • Состояние: <?php echo $state; ?>
  • Адрес электронной почты: &ЛТ;?PHP Эхо $электронной почты; ?&ГТ;
  • Хобби/интересы: <?php echo $hobbies; ?>



Обновить Учетную Запись |
Удалить Учетную Запись





Что я уже пробовал:

Я пробовал использовать echo $row, но у меня ничего не получилось

$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);

echo ($row);

mysqli_free_result($result);
mysqli_close($conn);
?>
<ul>

Richard MacCutchan

Что - но ты же не работал" значит? Пожалуйста, предоставьте надлежащие сведения о вашей проблеме и объясните, где в вашем коде произошла ошибка.

1 Ответов

Рейтинг:
0

Chad3F

Это работает?

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

$username = $row["username"];
$first_name = $row["first_name"];
$last_name = $row["last_name"];
$city = $row["city"];
$state = $row["state"];
$email = $row["email"];
$hobbies = $row["hobbies"];

Или:
$row = mysqli_fetch_array($result, MYSQLI_NUM);

$username = $row[0];
$first_name = $row[1];
$last_name = $row[2];
$city = $row[3];
$state = $row[4];
$email = $row[5];
$hobbies = $row[6];

Первый (с использованием MYSQLI_ASSOC), вероятно, является более гибким, так как изменения в порядке выбора столбцов не нарушат его. Но MYSQLI_NUM было бы немного эффективнее, если бы обрабатывалось большое количество строк (здесь это не так).

Да, и не забудьте добавить недостающее mysqli_real_escape_string() обертки в вашем первом блоке кода (например, $sql = 'SELECT username FROM site_user WHERE username = "' . $username . '"';).