PHP HTML SQL Passing Parameters to Update Database [duplicate] - php

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 months ago.
I am very new to the subject of PHP and SQL working together and I have been fine so far except for updating a database row on my SQL database. I'm using parts of my lecturers code and doing exercises and my own tasks to modify the webpages and behaviour.
The process of this code is to update an article that I have set up, so I can edit the title or the code then click confirm but when I do this I get my failed return message telling me there is a parameter problem. I have often had trouble passing parameters in other languages and I have been looking and testing this for a few hours that I am hoping to receive some information and guidance on the subject.
All I want to do is update the articletext and articletitle fields.
My EDIT ARTICLE code section:
<?php
$db=createConnection();
// get the first two articles
$sql = "select blogID,articletitle,articletext,blogtime,blogposter,username,userid from blogarticle join registerdemo on blogposter = userid where blogID=?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i",$article);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($articleid,$articletitle,$articletext,$blogtime,$blogposter,$username,$userid);
//build article html
while($stmt->fetch()) {
echo "<article id='a$articleid'>
<h1>$articletitle</h1>
<p>".nl2br($articletext)."</p>
<footer><p>Posted on <time datetime='$blogtime'>$blogtime</time> by <em>$username</em></p></footer>";
// if user is logged in and not suspended add comment button
if($currentuser['userlevel']>2 || ($currentuser['userid']==$userid && $currentuser['userlevel']>1)) {
?> <form method='post' action='applychanges.php'>
<input type="text" name="articletitle" id="articletitle" size="30" required value="<?php echo $articletitle; ?>"/><br />
<textarea name="articletext" id="articletext" cols="60" rows="5"><?php echo $articletext; ?></textarea></br>
<button type="submit">Confirm</button>
</form>
<?php
}
echo "</article>";
}
$stmt->close();
$db->close();
?>
My APPLY CHANGES code:
This is where the parameters fail
<!doctype html>
<html lang="en-gb" dir="ltr">
<head>
</head>
<body>
<?php
include('php/functions.php');
if(isset($_POST['articleid']) && isset($_POST['articletitle']) && isset($_POST['articletext'])) {
$db=createConnection();
$articleid=$_POST['articleid'];
$articletitle=$_POST['articletitle'];
$articletext=$_POST['articletext'];
$updatesql="UPDATE blogarticle SET articletitle='$articletitle', articletext='$articletext' WHERE articleid='$articleid'";
$doupdate=$db->prepare($updatesql);
$doupdate->bind_param("ssi",$articletitle,$articletext,$articleid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: index.php");
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
print_r($_POST);
}
?>
</body>
</html>
Result:
Some parameters are missing, cannot update database
Array ( [articletitle] => THIS IS A TEST [articletext] => hey )

You are not posting all the parameters with your form. For example, the textarea is missing the name attribute. This will result in not posting this form field your script. Add the following line to your "Apply changes" code. This will print out the parameters you are posting.
print_r($_POST);
Check which parameters are not posted.
You probably want to add some hidden form fields.

The Update query needs to include the data variable names . Query needs to be as follows:
$updatesql="UPDATE blogarticle SET
articletitle='$articletitle', articletext='$articletext' WHERE articleid='$articleid'";

Related

Eror in SQL syntax: Update query

I am a beginner to PHP and I am working on a profile page. The current problem is to change the name (This is a trial page that's why i am changing the name).For some reason i am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'lastName ='Lname' WHERE email ='qwerty#example.com'' at line 1.
<?php
include('server.php');
$db = mysqli_connect('localhost','root','','userdata');
$query = "SELECT * FROM data WHERE email = '".$_SESSION['username']."'";
$result = mysqli_query($db,$query);
$data = mysqli_fetch_assoc($result);
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<form method="POST" action="">
<p>First name: <input type="text" name="fname" value="<?php echo htmlspecialchars($data['firstName']); ?>" > </p>
<p>Last name: <input type="text" name="lname" value="<?php echo htmlspecialchars($data['lastName']); ?>"> </p>
<p><input type="Submit" name="confirm" value="Confirm"></p>
</form>
<?php
if(isset($_POST['confirm']))
{
$db = mysqli_connect('localhost','root','','userdata');
$query = "UPDATE data SET firstName ='".$_POST['fname']."' lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
mysqli_query($db,$query);
echo mysqli_error($db); //For checking error.Remove afterwords.
}
?>
<p>HOMEPAGE</p>
</body>
</html>
The server.php is a page where I manage the backend of the entire operation so it's not involved in this operation.The first PHP block takes data from the table. The HTML block creates a form where the user can edit the data. The PHP block should update data into the table.
I would appreciate any tips to further improve my page as i am still new to this.Thanks in advance
UPDATE:- Adding , to the query still does not change the situation.
you have an error in your sql statement (as the error message suggests). in mysql the error message usually points out the exact position where the error occurs, and it usually quotes the first character/word that causes the problem.
in your case, that's lastname. Your update query so far is:
UPDATE data SET firstName ='fname' lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ error occured here
when you look-up how UPDATE queries are supposed to look like (mysql docs) you'd find, that the different updated fields must be separated by comma:
UPDATE data SET firstName ='fname', lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ add this here
also, you're vulnerable to sql injections (please read up on them, and how to prevent them - this is done by prepared statements)
Please try with that(there was a missing comma on your SQL query).
$query = "UPDATE data SET firstName ='".$_POST['fname']."', lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
The other problem of using code that is open to sql injection is you can easily change the syntax of an sql statement from the input side. For example if for last name you input "O'connor", you change the syntax. Try to use echo $query and then analyse the output or better still,copy it and run it directly without using php
As mentioned in the comment. When updating multiple fields you need to comma separate them:
UPDATE data
set
field1="meh", /* <-- comma */
field2="foo"
where otherField="something"

Re-populating / Editing HTML form inputs using MySQL Data

Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...

Pass PHP fetch variable to another page

I have a form that submits to firstpage.php, this page includes the code to insert all form values into the database and check for duplicate entries, if the entry is a duplicate , display the duplicate entry using the following php code
$checkstudentID = mysqli_query
($dbcon, "SELECT studentid from courses WHERE studentid = '$studentid'");
if(mysqli_num_rows($checkstudentID) > 0){
if ($stmt = mysqli_prepare($dbcon, "SELECT ckb from courses WHERE studentid = ?")) {
mysqli_stmt_bind_param($stmt,"s",$studentid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $ckb);
mysqli_stmt_fetch($stmt);
printf("<br /><center><h1>Your Student ID is</h1> <h2>%s.</h2><h1> Subjects Registered : %s\n </h1>", $studentid, $ckb );
mysqli_stmt_close($stmt);
}
mysqli_close($dbcon);
die(" <p> The Student ID <strong>$studentid </strong>already exists. Update</p>");
the page update.html includes an update form that submits to update.php
how can I pass the the single fetched row variable (subjects registered/$ckb) to update.html ?
I tried the following so far:
at the firstpage.php I started a session
session_start();
$_SESSION['subjects'] = '$ckb';
and at the update.html > renamed to update2.php and added the following at the top of the page
<?php
session_start();
echo $_SESSION['sujects'];
?>
and at the input field the value="<?php echo $ckb;?>"
What am I missing ?
Please note, that the variable I want to pass is the subjects registered related to the student id checked in firstpage.php file meaning this :
printf("<br /><center><h1>Your Student ID is</h1> <h2>%s.</h2><h1> Subjects Registered : **%s**\n </h1>", $studentid, $ckb );
but its either completely wrong or I'm just passing the wrong variable
Remove quotes in:
$_SESSION['subjects'] = '$ckb';
So it will be:
$_SESSION['subjects'] = $ckb;
And update 2nd file to this:
<?php
session_start();
$ckb = $_SESSION['subjects'];
?>
....
<input type='text' value="<?php echo $ckb;?>" />
Note: also, you wrote sujects in second file, its ok in my code example.
In answer to my question I found an easy and effective by passing the variables through the url.
Meaning...
In my firstpage.php, the href links to my update2.php page became as follows:
Update
The $studentid and $cc variables are previously defined in my code where I "get" them from the input fields of the form.
In update2.php, the page which I would like to pass the variables to I inserted the following code
<?php
$studentid= $_GET['studentid'];
$cc = $_GET['ckb'];
?>
Which allowed me to use the variables throughout the rest of the php code, where for my case I wanted them to be the "values" of a new form input field, as shown below :
<input name="newcourses" type="text" id="newcourses" maxlength="70" value="<?php echo $cc?>"" />
I recommend anyone who wants a more clear idea and read more about other methods to pass variables across php pages to check this out >> Pass PHP fetch variable...

Empty rows created by refreshing page

I've searched on the Internet to get my answer, but I couldn't find a helpful one. I've got a page called 'post.php' with a form where I can add an image and submit it to the database.
The big problem is when I go to mysite.com/post.php a new empty row is created automatically in the database, which I clearly don't want. I want only to update the database after clicking on the submit button my code:
the part of INSERT:
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_POST['cat'];
// insert data to mysql
$sql = "INSERT INTO post(id, title, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if(!$result){
echo "Something went wrong!";
}
else {
echo "Yeah, buddy! Your content is added.";
}
// end of post script ^^
?>
// end of insert
//POST IMAGE PAGE
if(isset($_GET['pic'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Add url of image;<br />
<input type="text" name="pic" id="pic"/><br />
<?php
echo '
Category game:
<select name="cat"> ';
$query2 = mysql_query("SELECT * FROM `category`");
while($row=mysql_fetch_array($query2)){
echo '
<option value="'.$row["nameID"].'">'.$row["name"].'</option> ';
}
?>
</select>
<input type="submit" onclick="this.disabled = true" name="submit" value="submit">
</form>
<?php
// end script of posting picture
}
?>
You need to add some conditional code around the part that inserts into the database, checking for if any values has been received (if($myvar){ // do stuff }).
Add the rest of your code, specifically the part that adds stuff to the database as that is what's causing you problems, not the code you posted.
You need to wrap the whole block of database insertion code in an if statement. That way, it will not execute until the form has been submitted and $_POST['submit'] has a value:
include 'config.php';
if (isset($_POST['submit'])){
// values from form
$id=$_POST['id'];
// etc... code stays the same down to:
echo "Yeah, buddy! Your content is added.";
}
}//end if (don't forget to add this last bracket)
Also, you should switch to mysqli or PDO, and use parameterized queries. Otherwise, your site is open to a variety of gnarly attacks via SQL injection. It's not that hard to switch, and very, very important.
Check if the post have been set on the file that handles the database input.
if(isset($_POST['pic'])){
//do something
}
else{ // handle the exeption}
Also, you should not use mysql_* functions anymore. they are unsafe and deprecated as-of php 5.5

MySQLI string Won't update Info

I can't find out why when I click my submit button it doesn't process the data. I currently have a query as such.
$link = mysqli_connect("$server", "$user", "$pass", "webdb");
$page = mysqli_real_escape_string($link, (string) $_POST['page']);
$content = mysqli_real_escape_string($link, (string) $_POST['content']);
$query = "UPDATE `pages` SET `content`='$content' WHERE `name`='$page'";
mysqli_query($link, $query);
mysqli_close($link);
header("location: index.php");
?>
To connect to this query I have my form that submits the data.
<form action="update_content.php" method="post">
<textarea name="content" cols="60" rows="10"></textarea>
<input type="hidden" name="page" value="Index" />
<br /><input type="submit" value="Update" />
</form>
Everything looks to be correct from where I stand. I've been racking my brain and looking all over the web for hours now and I cannot find a solution here.
Step 1 :
Print the query variable, so that you can know the query is constructed well.
(Comment the redirection so that you can see the query output)
Step 2:
If the values passed in the query aren't correct or empty, fix this by printing the
passed params (you can print $_REQUEST - Which will show all the values posted)
Step 3
if all these are correct and if the query is not executed correctly, then check your
database connection.
You can print out the connection variable $link to see if a connection is made successfully.
These these steps will help you sort out the issue.
Let me know if these steps doesn't help you.
The actual answer was when the redirect was disabled I was able to see that the connection was failing which was something I wasn't able to see until the redirect was disabled in order to see the echo $query string. Lesson Learned: Check to ensure all variables are correct. :)

Categories