How to UPDATE only filled input with a submit button? - php

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;
}

Related

duplicate row formed in table when using PHP to store a form

I am making a site to display the family relations of an individual...I made use of PHP to store data from a form. I use access code to categorize different relations if an individual. i.e..101-the relations of person X.
I need a bit of help as to why to an entry is being entered twice into the database.(new to PHP and first time asking for help here)
Thank you in Advance!
forms code(IN ct.php):
<form id="frm1" action="ap.php" method="POST">
access code: <input type="text" name="code_entered" value=""><br><br>
position in family: <select name="fpos_entered">
<option>Grandfather</option>
<option>Grandmother</option>
<option>Father</option>
<option>Mother</option>
<option>Brother</option>
<option>Sister</option>
<option>Uncle</option>
<option>Aunt</option>
<option>Nephew</option>
<option>Niece</option>
<option selected>Yourself</option>
</select><br><br>
name: <input type="text" name="name_entered" value=""><br><br>
DOB:<input type="date" name="dob_entered" value=""><br><br>
<input type="submit" value="Submit">
</form>
i use the following PHP code to store the data from the form:
<?php
include 'ct.php';
$temp="temp";
$conn= mysqli_connect ('localhost','root','','familytree');
if (!$conn)
{
die ('Could not connect:' . mysql_error());
}
if (isset($_POST['code_entered']))
{
$acc= $_POST['code_entered'];
}if (isset($_POST['fpos_entered']))
{
$fpos= $_POST['fpos_entered'];
}if (isset($_POST['name_entered']))
{
$n= $_POST['name_entered'];
}if (isset($_POST['dob_entered']))
{
$db= $_POST['dob_entered'];
}
$sql ="insert into temp values ('$acc', '$n','$fpos','$db')";
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
which results in me having :
pic of the database after 2 enteries
<?php
declare(strict_types=1);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "familytree";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
try {
$stmt = $conn->prepare("
INSERT INTO `temp` (code, fpos, name, dob)
VALUES (:code, :fpos, :name, :dob)");
$stmt->bindParam(':code', $_POST['code_entered'] ?? null);
$stmt->bindParam(':fpos', $_POST['fpos_entered'] ?? null);
$stmt->bindParam(':name', $_POST['name_entered'] ?? null);
$stmt->bindParam(':dob', $_POST['dob_entered'] ?? null);
$stmt->execute();
echo "<p>New record created successfully</p>.";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
I recommend you to use PDO instead of mysqli. Also, bind the attributes coming from outside :)
Official docu: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
you can change the code of this
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
into this
$result = mysqli_query($conn,$sql);
if ($result === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and also you must to be careful about sql injection so i think you must use this

Trying to compare a value from the database from the url after the?

I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string

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>

What did i do wrong? Html is confusing itself

I'm making a page where you have to enter a text in a textbox and the click send, another page will save it.
Also, on the first page, the text that was stored previously in the database, has to load. This is the code that i've got:
<?php
$databaseid = 3;
$servername = "jog4fun.be.mysql";
$username = "jog4fun_be";
$password = "****";
$dbname = "jog4fun_be";
$gettitel1 = null;
$gettext1 = null;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Id,Titel,Tekst FROM Teksten";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
}
} else {
echo "0 results";
}
$conn->close();
$gettitel1 = strip_tags($gettitel1, '<br>');
$link1 = '<textarea id = "klein" rows="4" cols="50" name="titel3" form="usrform">' . $gettitel1 . '</textarea>';
$link2 = '<textarea id = "groot" rows="4" cols="50" name="text3" form="usrform">' . $gettext1 . '</textarea>';
echo $link1;
echo $link2;
?>
The problem is that it sends the text from textbox with name text3 as text1 with the post function. Can someone figure out what's wrong with it? I've been tying for an hour and i did not find it.
Thanks for your time and help,
Jonas
Simply here:
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
you overwrite the value of the two variables each time you iterate. So after this block of code you will keep stored the last values returned from the db.
YOu should add to your query a WHERE clause to identify the one and only record you need so you will fetch only the relevant data. Example:
$sql = "SELECT Id,Titel,Tekst FROM Teksten WHERE Id='1'";

Getting value from dropdown and use it in query

i am having trouble in deleteing values from my database using php can someone help me plsss this is for my project
this is where i get the value
<select name="fname" id='mySelect' value='Foodname'>
and this is what i want to do after i submit it
if(isset($_POST['submit']))
{
$food = $_POST['fname'];
echo $food;
if($food=='')
{
echo"<script>alert('Please Dont Leave any Blanks')</script>";
}
else
{
sqldel="DELETE FROM menu WHERE food = $food;";
}
}
This is how your complete code should be look like. Hope it helps!!!
<form name="" method="post" action="">
<select name="fname" id='mySelect' value='Foodname'>
<option value="">select</option>
<option value="option1">option1</option>
<option value="print server, printer">print server, printer</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
<?php
//Check if Form is submitted
if(isset($_POST['submit']))
{
//Store submitted value in variable
$food = $_POST['fname'];
echo $food;
//Check if the submitted value is blank or not
if($food=='')
{
//User submitted blank value - so throw an error
echo"<script>alert('Please Dont Leave any Blanks')</script>";
}
else
{
/*user selected a valid value in drop down so we are in else part*/
//This is your database configuration settings
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "yourDBName";
// Create connection - here you are doing database connection
$conn = new mysqli($servername, $username, $password, $dbname);
/* Check connection - If you database configuration settings are wrong it will throw an error and stop there itself and wont execute your further code*/
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/*Now Check if record exists in db for the selected value. If record exists in database than only we can delete record.*/
$sql = "SELECT id FROM menu WHERE food = '".$food."'";
$result = $conn->query($sql);
/*check if select query return a row greater than 0, implies record exists in table */
if ($result->num_rows > 0) {
/*Record exists in database so - sql to delete a record*/
$delete_sql = "DELETE FROM menu WHERE food = '".$food."' ";
/*this will execute the delete query, if it return true we will show success alert else throw an error*/
if ($conn->query($delete_sql) === TRUE) {
echo"<script>alert('Record deleted successfully')</script>";
} else {
echo "Error deleting record: " . $conn->error;
}
} else {
echo"<script>alert('No record found for the seleted item')</script>";
}
//Close database connection
$conn->close();
}
}
?>
just remove ; after query and put single quote around variable $food
sqldel="DELETE FROM menu WHERE food = $food;";
shoulb be
sqldel="DELETE FROM menu WHERE food = '$food'";
Here is a fix for your query:
$sqldel = "DELETE FROM menu WHERE food = '".$food."'";
You need to put quotes around $food.
$sqldel="DELETE FROM menu WHERE food = '$food';";

Categories