So, I have a form like so:
<form action="edit.php" method="POST" id="content">
<h3>Homepage</h3>
<hr/>
<h4>Title: </h4><input type="text" name="UserData[]" value='$UserData[]'><br/>
<h4>Subtitle: </h4><input type="text" name="UserData[]" value='$UserData[1]'><br/>
<h4>Footer: </h4><input type="text" name="UserData[]" value='$UserData[2]'><br/>
<input type="submit" value="Save" name="datasave" id="save">
</form>
PHP submit:
if(isset($_POST['datasave']))
{
$data = $_POST['UserData'];
$Userdata = mysqli_escape_string($con, $data);
$query = "UPDATE users
SET UserData = '$UserData' WHERE Username = '$Username'";
mysqli_query($con, $query);
}
Getting values from DB to display in fields:
$GetUserData = "SELECT UserData FROM users WHERE Username = '$Username'";
$UpdatedUserData= mysqli_query($con,$GetUserData);
if (! $UpdatedUserData){
echo "error";
}
while($row = mysqli_fetch_assoc($UpdatedUserData)){
$UserData = $row['UserData'];
}
I should probably note that I am a novice PHP & mysql user (please bear with me). The problem is, this doesn't work and I'm obviously missing something & not doing this as efficiently as I could be... How can I get the values of my multiple inputs and store them in the same db field? As you can see, I'd like each of the values to automatically be added to their respective field on page load.
EDIT: I have taken this down to barebones (removing other code etc.) and restructured a bit, which has done the trick! Now to learn about parameterized queries :D
<?php
require('config.php');
session_start();
$Username = $_SESSION['username'];
$GetUserData = "SELECT UserData FROM users WHERE Username = '$Username'";
$UpdatedUserData= mysqli_query($con,$GetUserData);
$row = mysqli_fetch_assoc($UpdatedUserData);
$data = json_decode($row["UserData"]);
foreach($data as $eachdata ) {
$UserData[] = $eachdata;
}
if ( $UserData ) {
echo '<form action="edit.php" method="POST" id="content">
<h3>Homepage</h3>
<hr/>
<h4>Title: </h4><input type="text" name="UserData[]" value="'.$UserData[0].'"><br/>
<h4>Subtitle: </h4><input type="text" name="UserData[]" value="'.$UserData[1].'"><br/>
<h4>Footer: </h4><input type="text" name="UserData[]" value="'.$UserData[2].'"><br/>
<input type="submit" value="Save" name="datasave" id="save">
</form>';
} else {
die("Error: {$con->errno} : {$con->error}");
}
if(isset($_POST['datasave']))
{
$data = json_encode($_POST['UserData']);
$query = "UPDATE users
SET UserData = '$data' WHERE Username = '$Username'";
mysqli_query($con, $query);
if (mysqli_query($con, $query)) {
header("Location: edit.php");
} else {
echo "Error updating record: " . mysqli_error($con);
}
}
if ( $con->connect_error ) {
die( 'Connect Error: ' . $con->connect_errno . ': ' . $con->connect_error );
}
$con->close();
?>