My problem is in updating the SQL record. It fetches SQL data into form correctly (For editing) but when I press save edits button it returns following erro inside input field:Notice: Undefined variable: row in C:\xampp\htdocs\edit.php on line 46Please can you tell me how to fix it
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "zz224466";
$database = "zain";
$conn = mysqli_connect($servername,$username,$password,$database);
if($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
if(isset($_GET['edit'])) {
$id = $_GET["edit"]; //Get id of sql table from other php page.
echo $id; //It gives true result. It means that $_GET method above gets id of sql table correctly
$res = mysqli_query($conn, "SELECT * FROM product where product_id=$id");
if ($res == FALSE) {
die("Error");
}
$row = mysqli_fetch_array($res);// Getting row from sql of specific id above selected above
if (isset($_POST['Edit'])) { ///Checking if Edit button has been pressed
$product_category = $_POST['product_category'];
$product_id = $id;
//// SQL query
$sql_category = "UPDATE product SET product_category='$product_category' WHERE product_id=$id";
if (mysqli_query($conn, $sql_category)) {
}
}
}
?>
////////////////////HTML FORM/////////////////////////
<form method="post" action ="edit.php" id="contact-form">
<input type="text" name="product_category" placeholder="product_category" value="<?php echo $row['product_category'];//It prints sql record in input field which is to be updated and it prints correctly. But when I press edit button it gives above mentioned error ?>"/>
<div class="btn-group" role="group">
<input type="submit" class="btn btn-default" name="Edit" value="Save Edits" style="margin-top: 15px; margin-right: 15px; border-radius: 4px;">
</div>
</form>
</body>
</html>
Kindly tell me that how to fix it
Try this. Because, when you are pressing submit button. It's going to edit.php with POST value and no GET parameters (after pressing Edit submit button. So, browser is unable to find $id resulting to it, no $row values.)
<input type="text" name="product_category" placeholder="product_category" value="<?php if(isset($row['product_category'])) { echo $row['product_category'];}?>"/>
for example, https:www.example.com/edit.php?edit=1
after pressing submit button, URL changes to
https:www.example.com/edit.php
So, no edit=1
Updated Code
Change your <form> to
<form method="post" action ="edit.php?edit=<?echo $_GET['edit'];?>" id="contact-form">
Additional to what i did before.
Full Updated Code (See lines where i have written Change Here)
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "zz224466";
$database = "zain";
$conn = mysqli_connect($servername,$username,$password,$database);
if($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
if(isset($_GET['edit'])) {
$id = $_GET["edit"];
echo $id;
$res = mysqli_query($conn, "SELECT * FROM product where product_id=$id");
if ($res == FALSE) {
die("Error");
}
$row = mysqli_fetch_array($res);
if (isset($_POST['Edit'])) {
$product_category = $_POST['product_category'];
$product_id = $_GET['edit']; // Change Here
// Changes here
$sql_category = "UPDATE product SET product_category='$product_category' WHERE product_id=$product_id";
if (mysqli_query($conn, $sql_category)) {
}
}
}?>
// Changes here in form tag
<form method="post" action ="edit.php?edit=<?echo $_GET['edit'];?>" id="contact-form">
<input type="text" name="product_category" placeholder="product_category" value="<?php if(isset($row['product_category'])) { echo $row['product_category']; }?>"/>
<div class="btn-group" role="group">
<input type="submit" class="btn btn-default" name="Edit" value="Save Edits" style="margin-top: 15px; margin-right: 15px; border-radius: 4px;">
</div>
</form>
</body>
</html>
Related
I've been going at this for a couple of hours now (searching here and google) but nothing I find helped me to get this to work.
I'm trying to make one form and have a Insert INTO and UPDATE $table SET function in the same form, using buttons.
But whatever I try the Update doesn't copy the data from the form. INSERT INTO works. But when I try to edit the form, no data is copied.
HTML:
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<input type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
Update
</div>
</form>
CMS_DATA.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "INSERT INTO $table (ID, Omschrijving, Datum, Tijd, Locatie, Dresscode )
VALUES ('" .$id."','" .$omschrijving."','".$datum."',' ".$item."','".$locatie."','".$dresscode."')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
UPDATE-CMS.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "UPDATE $table SET
Omschrijving = '$omschrijving', Datum = '$datum', Tijd = '$item', Locatie = '$locatie', Dresscode = '$dresscode' WHERE ID = '1'";
if ($conn->query($sql) === TRUE) {
echo "Done";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Like I said, the INSERT INTO works fine. But no data (values) are copied when using the update. I just overrides ID 1 with empty rows... I hope someone can help me... thanks in advance.
You have defined action on your form action="cms_data.php", so your button that is responsible for submitting that form works correctly, but on the other hand you've defined another button (anchor tag), that only has href (hence points to another page), so if you click on it, you won't pass any arguments with it.
My suggestion here is, as I mentioned in comment below your question, to use two buttons, both with submit property, but then handle clicking on them via JavaScript.
When you capture submitment, you can dinamically change action on your form, so your data will be passed to desired script.
Handling multiple buttons in a form:
Process a Form Submit with Multiple Submit Buttons in Javascript
Manipulating form's action property:
How to use JavaScript to change the form action
Another suggestion would be that you use prepared statements in your query, so you wouldn't be vulnerable to SQL injections (from the comments section, I see you'll only be using this locally, but this is a good practice).
Using Mysqli prepared statements:
https://stackoverflow.com/a/24989090/5018750
Echo only prints value on the screen in your respective textbox and does not assign that value to your actual field.
Instead what you can do is start the session in the start of your contact form and store those fields in session variable.
When user selects UPDATE option he will get redirected to UPDATE-CMS.php page. In UPDATE-CMS.php you can retrieve your stored session variables and assign them to your actual variables. In this way you can carry forward your old as well as new values.
anchor just links the page it will not pass data
you are trying to have submit and update button in one form
solution:
in html5 button has formaction attribute .formaction specifies page data to be transferred .so that different button can have different action page
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<buttin formaction="CMS-DATA.php" type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
<button formaction="UPDATE-CMS.php" >Update </button>
</div>
</form>
I am trying to use a search bar to grab the users input but when i input and submit nothing happens, I its not submitting properly but i can't for the life of me find my mistake. I have copied the input code from a previously created login page which works fine and therefore baffles me even more.
<div class="container">
<div class="form-group">
<?php
$stocksymbol = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["stocksymbol"])) {
$stocksymbolErr = "Please enter Username.";
} else {
$stocksymbol = test_input($_POST["stocksymbol"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}}
$servername = "localhost";
$username2 = "root";
$password2 = "";
$dbname = "mydb";
$mysqli = new mysqli($servername, $username2, $password2, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$query = "SELECT * FROM tblstocks WHERE Symbol = '$stocksymbol'";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$_SESSION['stockavailable'] = true;
$_SESSION['stock']= $row;
header('Location: item.php');
}
$result->free();
}
$mysqli->close();
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="stocksymbol">Search:</label>
<input type="text" class="form-control" id="stocksymbol">
<br><br>
<input type="submit" class="btn btn-default" name="submit" value="Submit">
</form>
</div>
The input element must have an attribute name with the value to be the key that you are expecting on the server i.e. stocksymbol to be able to receive whatever entered in the element.
<input type="text" class="form-control" id="stocksymbol" name="stocksymbol">
Right now I am trying to create a edit form for my forum, and while I CAN get it to edit, it does not insert an ID to the database (rendering it 0 and thus faulty), the ID field have Auto increment and I've double checked it is the primary field. Tried looking over it many times, but there's got to be something I am missing.
The DB connection:
<?php
error_reporting(E_ALL);
session_start();
$host = 'HOSTNAME';
$dbusername = 'USERNAME';
$dbpassword = 'PASSWORD';
$anslutning = mysqli_connect($host, $dbusername, $dbpassword) or die("<b>Could not connect to database server</b>");
$anslutning->select_db('DATABASE NAME') or die("<b>Could not connect to the specified database</b>");
?>
The form where you edit the post ($edit in this scenario is the ID it grabs when clicking "edit" on a post), as well as where I try to update the database field.
<?php
if(isset($_GET['edit'])) {
// If click on "edit"
$edit = $_GET['edit'];
// The post-editing ID
$getEditData = $anslutning->prepare("SELECT postId, title, content FROM tblPosts WHERE postid='$edit' LIMIT 1");
$getEditData->bind_result($postId, $title, $content);
$getEditData->store_result();
$getEditData->execute();
while($row = $getEditData->fetch()) {
echo '
<div class="editForm">
<form action="index.php" method="POST">
<input type="hidden" name="author" value="'.$_SESSION['loggedIn'].'">
<input type="hidden" name="edit" value="'.$edit.'">
Title: <input type="text" name="new_title" value="'.$title.'"> <br /> <br />
Content: <textarea name="new_content"> '.$content.' </textarea> <br /> <br />
<input type="submit" name="editPost">
</form>
</div>
';
}
}
// Issue(s): Editing a post does not send postId/edit(id) to database
if(isset($_POST['editPost'])) {
$edit = $_GET['edit'];
$author = $_POST['author'];
$new_title = $_POST['new_title'];
$new_content = $_POST['new_content'];
$updatePost = $anslutning->prepare("UPDATE tblPosts SET postId=?, author=?, title=?, content=?");
$updatePost->bind_param("isss", $edit, $author, $new_title, $new_content);
$updatePost->execute();
echo 'Post updated. Redirecting..';
sleep(1);
echo '<script> window.location.href = "index.php?forum=1" </script>';
}
?>
Change
$edit = $_GET['edit'];
to
$edit = $_POST['edit'];
i am a PHP MYSQL beginner! trying to get the id (primary key) value of a row and update its corresponding values in a database. My search results are working perfecting and am getting redirected to my update form page, where in which i wanted to display the fetched result, so that i can edit the result and update the values.
My PHP
<?php
require_once 'db_alternate2.php';
session_start();
try{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= "SELECT * FROM staff_db WHERE staff_id='$id'";
$r = $conn->query($res);
$r->setFetchMode(PDO::FETCH_ASSOC);
}
if( isset($_POST['new_staf_id']) && isset($_POST['new_staf_name']) && isset($_POST['new_staf_acc']) && isset($_POST['new_staf_bnkaddrs']) )
{
$staf_id = $_POST['new_staf_id'];
$staf_name = $_POST['new_staf_name'];
$staf_acc = $_POST['new_staf_acc'];
$staf_bnkaddrs = $_POST['new_staf_bnkaddrs'];
$sql = $conn->prepare("UPDATE staff_db SET staff_id='$staf_id' staff_name='$staf_name' staff_acc='$staf_acc' staff_bnkaddrs='$staf_bnkaddrs' WHERE sl_no ='$id'");
$sql->execute();
$result1 = $sql->fetch(PDO::FETCH_ASSOC);
echo "<meta http-equiv='refresh' content='0;url=staff_update.php'>";
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?> .
My HTML
<form class="" style="right:10px !important;" action="staff_db.php" method="post">
<div class="main-left" style="width:38% !important; margin-left:100px;">
<p>Staff ID:</p> <input type="text" name="staf_id" value="______"/>
<p>Name:</p> <input type="text" name="staf_name" value="______"/>
</div>
<div class="main-right" style="width:38% !important; margin-right:100px;">
<p>Account no:</p> <input type="text" name="staf_acc" value="______"/>
<p>Bank Address:</p> <input type="text" name="staf_bnkaddrs" value="______"/>
</div>
<div class="bottom-centre" style="padding-top:50px; ">
<input class="submit" type="submit" value="Update"/>
</div>
</form>
I know this is a simple question, but guide me here! how to display the PDO fetched results inside the value="______" of form.
Thanks in advance!
Just few modifications in your code
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= "SELECT * FROM staff_db WHERE staff_id='$id'";
$r = $conn->query($res);
$r->setFetchMode(PDO::FETCH_ASSOC);
$result = $r->fetch();
}
and few modification in your form to put value
<input type="text" name="staf_name" value=<?php echo $result["staff_name"]; ?>/>
I'm currently managing a little database for a club and I'm starting to feel more and more pressure to update the thing to PHP5. The only thing is that I'm not quite a 100% sure on how to convert this structure without messing up the whole thing. (Or starting from scratch)
Could you guys tell me if this is easily editable/updatable or if I should redo everything? (The total file is 800 lines, so I hope to not have to redo it :P)
So I open the databse with:
//Database connection settings
$mysql_server = "localhost";
$mysql_user = "user";
$mysql_password = "pass";
$mysql_database = "database";
//Connect using settings
$connection = mysql_connect("$mysql_server","$mysql_user","$mysql_password")
or die ("Unable to connect to MySQL server.");
$db = mysql_select_db("$mysql_database")
or die ("Unable to select requested database.");
Then I can create users with:
if($changeme ==1) //if user pressed save, then update table
{
$name = mysql_real_escape_string($_POST["name"]);
mysql_query("INSERT INTO Members (name,) VALUES
('$name')") or die(mysql_error());
//show end text
echo "Edit complete!<br />
<form><input type='button' onClick=\"parent.location='users.php'\" value='OK'></form>";
}else{//user didn't press save
?>
<!--Edit form-->
<form action="users.php?new=1&changeme=yes" method="post">
Naam:<br>
<input name="name" type="text" value="" size="79"><br>
<input type="submit" name="Submit" value="Create">
<input type='button' onClick="parent.location='users.php'" value='Back to list'>
</form>
}
I left out everything but name to make it shorter, it has like 30 fields.
Next we can also edit the profiles like this:
if($changeme ==1) //if user pressed save, then update table
{
$id = $_POST['id']; //get ID from form
$name = $_POST["name"];
mysql_query("UPDATE Members SET name='$name' WHERE id='$id'") or die(mysql_error());
//show end text
echo "Edit complete!<br />
<form><input type='button' onClick=\"parent.location='users.php'\" value='OK'></form>";
}else{//user didn't press save
$id = $_GET['edit'];
$sql = "SELECT * FROM Members WHERE id='$id'";
$self = mysql_query($sql);
while ($row = mysql_fetch_array($self)) {
$name = $row["name"];
}
?>
<!--Edit form-->
<form action="users.php?edit=<?php echo $id ?>&changeme=yes" method=post>
<input type="hidden" name="id" value="<?php echo $id ?>">
Name:<br>
<input name="name" type="text" value="<?php echo $name ?>" size="79"><br>
<input type="submit" name="Submit" value="Change">
<input type='button' onClick="parent.location='users.php'" value='Back to list'>
</form>
<?php
}//didn't press save