hope we are having a great week of coding and experimenting!
I'm working on a CMS-like project and need some help to get my data storage working properly. The problem at the moment is that I'm not sure if I should be using PHP objects, arrays, or both, and I'm not too sure of how to go about using them in an instance like this. (I'm kinda new to php / mysql and some guidance and examples would be great!)
So, I have a db called "Project X" with a table called "users". I've created a column named "UserData" in which I intend to store a user's page settings and content.
Currently, the user types names of the "pages" they want in a CSV-formatted input field, which gets saved to their UserPages field in the db and then for each page, a form is displayed like so:
$UserPages = null;
if ($stmt = $con->prepare("SELECT UserPages FROM users WHERE Username=?")) {
$stmt->bind_param("s", $Username);
$stmt->execute();
$result = $stmt->get_result();
$row = mysqli_fetch_assoc($result);
$UserPages = $row['UserPages'];
$Pages = explode(',', $UserPages);
while($data = mysqli_fetch_array($result)){
$UserPages .= $data['UserPages'];
$badchars = array("[", "]","'" );
$UserPages = str_replace($badchars , '', $UserPages);
}
}
foreach ($Pages as $Page) {
echo "<form action=" .$_SERVER['PHP_SELF']. " method='POST' id=" . $Page . ">";
$PageForm = "<h3>" . $Page . "</h3>
<hr/>
<h4>Title: </h4><input type='text' name='".$Page."[]' value='".$UserData['Title']."'><br/>
<h4>Subtitle: </h4><input type='text' name='".$Page."[]' value='".$UserData['Subtitle']."'><br/>
<input type='submit' value='Save' name='".$Page."' id='save'>";
print_r($PageForm);
echo "</form>";
}
?>
The forms display like so:
<form action="/phplogin/v2/edit.php" method="POST" id="Home">
<h3>Home</h3>
<hr>
<h4>Title: </h4><input type="text" name="Home[]" value="Title"><br>
<h4>Subtitle: </h4><input type="text" name="Home[]" value="Subtitle"><br>
<input type="submit" value="Save" name="Home" id="save">
</form>
Now, this does work (kinda), but I need to correctly (and dynamically) get and store the data from these various "Pages" and store them as arrays within an object, which is then JSON encoded and stored back in the UserData column.
The code I'm using at the moment fails miserably, only replacing the data in UserData field with "Save" lol...
if(isset($_POST[$Page])) {
$data= $_POST[$Page];
$stmt = $con->prepare("UPDATE users SET UserData = ? WHERE Username = ?");
$stmt->bind_param('ss', $data, $Username);
$stmt->execute();
$stmt->close();
header('Location: '.$_SERVER['PHP_SELF']);
die;
}
So I guess my main question is, how to get the data for each page into it's own array, and then combine the arrays + json encode and store.
A pic of it: