PHP Multiple forms on same page with multiple buttons - php

I'm busy coding a website for a local business that does Milkshakes. Naturally, they wanted to show their flavours on the site and have a management page where they could edit them. I have gotten the flavours to show up on the main page, but I am having a problem with the management page.
I have a database set up that contains a list of the flavours. The 3 main things that I am trying to allow them to do is edit, delete and add new entries. Currently, I am calling out each row (or each flavour and its id) as separate forms with 2 submit buttons: one to save changes, and one to remove it.
Code is below:
for the management page:
<?php
$con = new PDO('mysql:host=host;dbname=dbname', "user", "password");
$con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM FlavourShakes";
$data = $con->query($query);
$rows = $data->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$flavour = $row['Flavour'];
print "<form action=\"saveFlavorShakes.php\" method=\"post\"> \n
<fieldset> \n
<input name=\"id\" value=\"$id\" readonly/> \n
<input name=\"Flavour\" value=\"$flavour\" /> \n
<input type=\"submit\" name=\"edit\" value=\"Save\"> \n
<input type=\"submit\" name=\"edit\" value=\"Remove\"> \n
</fieldset> \n
</form> \n";
}
?>
<form action="saveFlavorShakes.php" method="post">
<fieldset>
<input name="Flavour" />
<input type="submit" name="edit" value="Add">
</fieldset>
</form>
and on my processing page:
<?php
$flavour = $_POST['Flavour'];
$id = $_POST['id'];
$btnType = $_POST['edit'];
$con = new PDO('mysql:host=hostname;dbname=dbname', "user", "password");
$con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "";
try
{
switch($_POST['edit']){
case'Save':
$query = "UPDATE FlavorShakes
SET Flavour= :name,
WHERE id = :id;";
$notice = "saveOK";
$_POST['notice'] = $notice;
break;
case'Add':
$query = "INSERT INTO FlavourShakes(Flavour) VALUES (:name);";
$notice = "addOK";
$_POST['notice'] = $notice;
break;
}
//I know I haven't added a case for the remove button yet.
$statement = $con->prepare($query);
$statement->bindValue(":id", $id);
$statement->bindValue(":name", $flavour);
$count = $statement->execute();
header('Location: EditFlavorShakes.php');
}
catch(PDOException $e) {
if ($btnType = "save"){
$notice = "saveBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
} elseif($btnType = "delete"){
$notice = "delBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}elseif($btnType = "add"){
$notice = "addBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}else{
$notice = "otherBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}
echo $notice;
echo $e->getMessage();
//header('Location: EditFlavorShakes.php');
}
?>
Currently, I don't have any entries in the database. However, when I try to add Chocolate and click the Add button, I get this error:
saveBadSQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
What I don't understand is why it $_POST['edit'] set to save instead of add? I feel like I am overlooking some stupidly simple mistake in my code. If anyone can help me I would appreciate it.
Thanks in advance.

You need to move the right $statement calls into each case -
switch($_POST['edit']){
case'Save':
$query = "UPDATE FlavorShakes
SET Flavour= :name,
WHERE id = :id;";
$notice = "saveOK";
$_POST['notice'] = $notice;
$statement = $con->prepare($query);
// this query needs multiple values bound
$statement->bindValue(":id", $id);
$statement->bindValue(":name", $flavour);
break;
case'Add':
$query = "INSERT INTO FlavourShakes(Flavour) VALUES (:name);";
$notice = "addOK";
$_POST['notice'] = $notice;
$statement = $con->prepare($query);
// this one needs one value bound
$statement->bindValue(":name", $flavour);
break;
}
//I know I haven't added a case for the remove button yet.
$count = $statement->execute();
You're also missing several tests (you're assigning) in your if statement. Replace = with == -
if ($btnType == "save"){
...
} elseif($btnType == "delete"){
...
}elseif($btnType == "add"){
...
}else{
...
}

This error message:
saveBadSQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
is because you try this line when there is no :id
$statement->bindValue(":id", $id);
And you always get saveBad cause you assign in your control:
if ($btnType = "save"){
Fix to:
if ($btnType === "save"){

Related

Is it possible to connect a button from another table to another table to get the data?

I have two tables in one database. The first one is the g1 where the buttons' data is located. The second is the gradeone, where the enrollees' data is located. I want to display the data from the table "gradeone" by clicking the
specific buttons.
Assuming that I added 2 sections. Section 1 and section 2. I click the button section1. By clicking it, I want to display the data of the enrollee from table "gradeone" where the section is 1.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$sectionnumber ="";
$datasuccess ="";
$error ="";
function getPosts(){
$posts = array();
$posts[1] = $_POST['sectionnumber'];
return $posts;
}
if(isset($_POST['add'])){
$data = getPosts();
if(empty($data[1])){
$error = 'Enter The User Data To Insert';
}else {
$insertStmt = $con->prepare('INSERT INTO g1(sectionnumber) VALUES(:sectionnumber)');
$insertStmt->execute(array(
':sectionnumber'=> $data[1]
));
if($insertStmt){
$datasuccess = "<font color='#f8234a'>New added</font>";
}
}
}
?> //Code for adding a button
<?php
require 'connection.php';
$sql = "SELECT sectionnumber FROM g1";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<button type='button' class='btn'>Section " . $row["sectionnumber"] . "</button></a><hr>";
}
} else { echo "<B>No Sections</B>"; }
$con->close();
?> //Code for displaying the button
<html>
<body>
<form action=">
<input type="number" name="sectionnumber">
<input type="submit" name="add">
</form>
</body>
</html>

Choose which mysql table to update in php post

I have a form handler (I believe that is the correct terminology) called insert.php, this is used to post form data to a MySQL database on localhost. I have different tables each containing a single record and would like to choose which table the data goes to. I could duplicate the insert.php file for each table but that seems messy. How do I choose which table the data goes to via post?
current insert.php:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: index.php');
mysql_close($con)
?>
What I think is needed for the $sql = variable:
$sql = "UPDATE '$_POST[myTable]' SET '$_POST[myField]' = '$_POST[myValue]' WHERE tableKey = 1"
My html is this:
<form action="insert.php" method="post">
<input type="text" name="myField" value="<?= $myValue ?>"/>
<input type="submit" value="Submit" />
what html should I be using to feed my revised insert.php file above, if that is correct? Thanks.
try this format
$sql = "UPDATE `".$_POST['myTable']."` SET `".$_POST['myField']."` = '".$_POST['myValue']."' WHERE `tableKey` = 1";
or
$mysqli = new mysqli("host", "user", "password", "db");
$stmt = $mysqli->prepare("UPDATE `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myTable'])))."` SET `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myField'])))."` = ? WHERE `tableKey` = 1");
$stmt->bind_param("s",$_POST['myValue']);
$stmt->execute();
You should use prepared statement instead
There's some wider practices that could be improve, but based on your current code/structure, I would use something like this:
<?php
require_once 'login.php';
try {
$con = new mysqli("host", "user", "password", "db");
} catch (mysqli_sql_exception $e) {
echo "Failed to connect to MySQL: ".$e;
}
$table = (isset($_POST['myTable'])) ? $_POST['myTable'] : null;
$reqdTemp = (isset($_POST['setTemp'])) ? $_POST['setTemp'] : null;
$tempKey = (isset($_POST['setKey'])) ? $_POST['setKey'] : null;
switch($table) {
case "thisTable":
$qry = "UPDATE `thisTable` SET thisField = ? WHERE thisKey = ?";
break;
case "thatTable":
$qry = "UPDATE `thatTable` SET thisField = ? WHERE thisKey = ?";
break;
case "anotherTable":
$qry = "UPDATE `anotherTable` SET thisField = ? WHERE thisKey = ?";
break;
default:
// do something?
break;
}
$stmt = $conn->prepare($qry);
$stmt->bind_param("si", $reqdTemp, $tempKey);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error;
}
else {
echo "1 record added";
}
header ('location: index.php');
mysql_close($con)
?>
Two things to note: The switch statement allows you to provide a different query based on the table name, but it assumes that the same structure is in place (i.e. update String Where Integer).
I've also assumed the thisKey is posted too, as 'setKey'.
Secondly, prepared statements.
This is more of a hint, rather than a whole solution, and you probably need to tidy it up and make it work for you outside of my assumptions

phpmyadmin not using DEFAULT value when input is left empty

I have this problem where if I leave my input for 'Title' blank, then it won't set the default value: "Untitled" when sent to the database. I've looked online and have made sure that my settings were correct in phpmyadmin but it still won't set the default value. Any piece of advice is appreciated!
Here are my PHPmyadmin settings for the "Title" column:
These are my files:
addart.php
<form method="post" action="addtodb.php">
<label for="Title">
<h4>Title</h4>
</label>
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="Title">
</form>
addtodb.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$dbConnection = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Could not connect to the mySQL database: %s\n", mysqli_connect_error());
exit();
}
if($_POST) {
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
$results = $dbConnection->query("INSERT INTO art
(Artwork, Title, Artist, Medium) VALUES
('$artwork','$title','$artist','$medium');");
if (!$results) {
echo 'Unable to insert into database.';
exit();
} else {
echo 'Successfully added!';
}
mysqli_close($dbConnection);
header("Location: galleryonly.php"); /* Redirect browser */
exit();
}
?>
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
if(!empty($title)) {
$sql = "INSERT INTO art (Artwork, Title, Artist, Medium) VALUES ('$artwork', '$title', '$artist', '$medium')";
} else {
$sql = "INSERT INTO art (Artwork, Artist, Medium) VALUES ('$artwork', '$artist', '$medium')";
}
$results = $dbConnection->query($sql);
You can try out this code.
If you're omitting the column, the default value will be set.
Because you have only one column with default value, you can stick with this code.
If you have more than one column with default value, you will need to make changes according to your requirements.
You have a bit of trick ahead of you, because you won't be able to use the Title column if you need the Default value.
// assuming use of proper method of sanitizing
// these values so we don't get SQL INJECTED!!
$artwork = 'artwork';
$title = 'title';
$artist = 'artist';
$medium = 'medium';
// make an array with the columns
$cols = explode(',', 'Artwork,Title,Artist,Medium');
// make an array with the values (that you sanitized properly!)
$vars = explode(',', 'artwork,title,artist,medium');
foreach ($cols as $i=>&$col) {
$var = ${$vars[$i]};
if ($col == 'Title') {
if (empty($var)) {
// don't add this column if empty
continue;
}
}
// otherwise (if not Title)
// add it to a column = "value" insert string
$pcs[] = "`$col` = '$var'";
}
// fortunately, we can insert with update syntax, too!
$query = 'insert into art set ';
$query .= implode(', ', $pcs);
use always small letters in
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="title">

How to UPDATE only filled input with a submit button?

PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

MySQL Query Issue - PHP variable not passed through includes

So as the title suggests, I am having trouble executing a MySQL query. The query works almost successfully, as all data fields are stored into my database except for one. The query itself is a commenting system for signed in users to comment on any given blog post. The issue I am having is that the variable '$post_id' is not recognized, and therefore '$comment_post_ID' is not stored in my database.
'$post_id' is defined in blogs.php, and after echoing this variable it does exist and is successfully defined. However, this variable is not passed onto commentsubmit.php, which is included in the same file where the variable is defined. Why is this happening?
Here are all the pieces of my code:
blogs.php (shows all posts from all users, or just one post if ?id is set in the url. If ?id is set, users can comment on the single post they are viewing.)
<?php
if (isset($_GET['id'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$post_id = mysqli_real_escape_string($conn, $_GET['id']);
$blog_post = "SELECT * FROM blogs WHERE id = '$post_id'";
$blog_query = mysqli_query($conn, $blog_post);
while ($row = mysqli_fetch_array($blog_query)) {
$title = $row['title'];
$body = $row['body'];
$author = $row['author'];
$author_username = $row['author_username'];
$datetime = time_ago($row['datetime'], $granularity=2);
}
include ("./fullpageblog.php");
if (isset($_SESSION['id'])) {
include ("./blogcomment.php");
include ("./commentsubmit.php");
}
echo "$post_id";
mysqli_close($conn);
}
?>
blogcomment.php (form for users to make a comment)
<div class="row col-sm-12">
<div id="fullPageBlog">
<div id="center-border"></div>
<form action="commentsubmit.php" method="post">
<textarea maxlength="1000" id="blogComment" name="content" placeholder="Write your response..."></textarea>
<input type="submit" name="comment" value="Publish" />
</form>
<script type="text/javascript">$('#blogPost').elastic();</script>
</div>
</div>
commentsubmit.php (comment query itself)
<?php
session_start();
if (isset($_POST['comment'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$comment_post_ID = $post_id;
$comment_author = $_SESSION['full_name'];
$comment_author_email = $_SESSION['email'];
$comment_author_username = $_SESSION['username'];
$comment_date = date("Y-m-d H:i:s");
$comment_content = mysqli_real_escape_string($conn, $_POST['content']);
$user_ID = $_SESSION['id'];
$comment_submit = "INSERT INTO comments (comment_ID, comment_post_ID, comment_author, comment_author_email, comment_author_username, comment_date, comment_content, user_ID) VALUES ('', '$comment_post_ID', '$comment_author', '$comment_author_email', '$comment_author_username', '$comment_date', '$comment_content', '$user_ID') ";
$comment_query = mysqli_query($conn, $comment_submit);
mysqli_close($conn);
header("Location: blogs.php");
die();
}
?>
You don't include/require the blogs.php script from the commentsubmit.php script, so the code in blogs.php would never be run after a POST that is made directly to commentsubmit.php unless you have some other request processing (i.e. a server-side rewrite or similar) that happens automatically on the server before the request ultimately reaches the portion of code shown in commentsubmit.php above.
<?php
$con = mysql_connect("localhost","root","password");
$con=mysql_select_db("database_name");
error_reporting(0);
session_start();
if(isset($_POST["submit"])){
$comment_author = $_POST['full_name'];
$comment_author_email = $_POST['email'];
$comment_author_username = $_POST['username'];
$sql="select * from table_name where `full_name`='"$comment_author "',`email`='"$comment_author_email "',`username`='"$comment_author_username "'";
$qur=mysql_query($sql);
$row= mysql_fetch_array($qur);
$num= mysql_num_rows($qur);
}
if($num>0){
$_SESSION["full_name"]=$full_name;
$_SESSION["email"]=$comment_author_email;
$_SESSION["username"]=$comment_author_username;
}
else{
echo"Username and Password are wrong";
}
?>

Categories