Data is not updated into database [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have a form that I use to insert data into database and a table in which I display the records from the same database. I have the update button on each record displayed.
When I click on it, the data from the database is displayed in each input from the form; I've modified the information that I want and click Update button from the form.
The problem is that the data I have modified is not updated in the database and is not displayed in the table of my page.
My index-admin.php file:
<?php
include("functions.php");
//fetch record to be updates
if(isset($_GET['update'])){
$id = $_GET['update'];
$update = true;
$query="SELECT * FROM utilizatori WHERE id_user= $id";
$record = mysqli_query($conn,$query);
if (count($record) == 1 ) {
$rec = mysqli_fetch_array($record);
$id=$rec['id_user'];
$nume=$rec['nume'];
$prenume=$rec['prenume'];
$email=$rec['email'];
$pwd=$rec['pass'];
$rol=$rec['rol'];
}
}
?>
My form:
<form method="POST" action="functions.php">
<input type="hidden" name="id" value="<?php echo $id; ?> ">
<div class="input-group">
<label>Nume</label>
<input type="text" name="nume" value="<?php echo $nume; ?>">
</div>
<div class="input-group">
<label>Prenume</label>
<input type="text" name="prenume" value="<?php echo $prenume; ?>" >
</div>
<div class="input-group">
<label>Email</label>
<input type="text" name="email" value="<?php echo $email; ?> ">
</div>
<div class="input-group">
<label>Password</label>
<input type="text" name="pass" value="<?php echo $pwd; ?> ">
</div>
<div class="input-group">
<label>Rol</label>
<input type="text" name="rol" value="<?php echo $rol; ?> " >
</div>
<div class="input-group">
<?php if ($update == false): ?>
<button type="submit" name="save" class="btn">Save</button>
<?php else: ?>
<button type="submit" name="update" class="btn">Update</button>
<?php endif ?>
</div>
</form>
My functions.php file:
if(isset($_POST['update'])) {
$nume = mysqli_real_escape_string($conn,$_POST['nume']);
$prenume = mysqli_real_escape_string($conn,$_POST['prenume']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$pwd = mysqli_real_escape_string($conn, $_POST['pass']);
$rol = mysqli_real_escape_string($conn, $_POST['rol']);
$query="UPDATE utilizatori
SET nume='$nume',
prenume='$prenume',
email='$email',
pass='$pwd',
rol='$rol'
WHERE id_user=$id;";
mysqli_query($conn,$query);
$_SESSION['msg'] = 'Date actualizate!';
header('Location:index-admin.php');
}

It seems that $id is undefined within functions.php. It only existed in index-admin.php, and when the form is submitted, that code is not running. Web applications are stateless and variable values do not persist between requests. Nor are variable values magically passed between separate script files (unless they are called within the same request via an "include" or "require" statement).
However you've actually partially solved that. You have already placed the ID within a hidden field in your form when index-admin is being loaded. Now you just need to create a new variable to read it in functions.php:
if(isset($_POST['update'])) {
$id = $_POST["id"];
As a separate point, I can't see why you also wrote include("functions.php"); within the index-admin script...your form posts back directly to functions.php, rather than to index-admin.php. It makes no sense to include functions.php within that page...it won't do anything useful as far as I can see.
Please pay attention to the warnings within the comments about SQL Injection. This is a serious vulnerability and you should fix it as soon as possible, preferably before you commence testing your code (so that you don't have to re-test it once you've re-written the query code).

Related

Trouble updating records in PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've created a website where I can upload articles however im having trouble with updating articles that have been created. I have managed to fill in a form with the information from the database pre-filled in but when i submit any changes then to the article then it does not update.
The $var_value is the primary key passed from the previous page to determine which article to load & edit.
Here is my form to update the article.
<?php
$var_value = $_POST['varname'];
$get_studies = "select * from news where `news`.`articleID` = $var_value";
$run_studies = mysqli_query($con,$get_studies);
while($row_studies = mysqli_fetch_array($run_studies)){
$newsTitle = $row_studies['title'];
$newsDate = $row_studies['date'];
$shortBio = $row_studies['shortBio'];
$longBio = $row_studies['longBio'];
$longBio2 = $row_studies['longBio2'];
$image = $row_studies['image'];
}
echo "
<div class='panelContent1' id='addNewsWraper'>
<h2>Dashboard</h2>
<h3>Update Article</h3>
<form method='post' enctype='multipart/form-data' onsubmit='alert('stop submit'); return false;' >
<div class='newsForm'>
<p>Article Title<br /><input type='text' value='$newsTitle' name='newsTitle' /></p>
<p>Short Description<br /><textarea name='newsShort' placeholder='Around a paragraph' />$shortBio</textarea>
<p>Image<br /><input type='file' name='newsImage' /></p>
</div>
<div class='newsForm'>
<p>Date<br /><input type='text' value='$newsDate' name='newsDate' placeholder='2017' /></p>
<p>Story<br /><textarea name='newsLong' placeholder='News article text' />$longBio</textarea>
<p>Story2<br /><textarea name='newsLong2' value='' placeholder='News article text' />$longBio2</textarea>
<button type='submit' name='updateNews'>
Update
</button>
</div>
</form>
</div>
";
?>
Here is how i am trying to update the article. I have tried to update the record based on a primary key, this variable is being passed to the page as its what is loading the content in the form.
<?php
if(isset($_POST['updateNews'])){
$newsTitle = $_POST['newsTitle'];
$newsDate = $_POST['newsDate'];
$newsShort = $_POST['newsShort'];
$newsLong = $_POST['newsLong'];
$newsLong2 = $_POST['newsLong2'];
$newsImage = $_POST['newsImage'];
$insertNews = "UPDATE mods SET title='$newsTitle', date='$newsDate', shortBio='$newsShort', longBio='$newsLong', longBio2='$newsLong2', image='$newsImage' WHERE articleID='$var_value'";
$updateNews = mysqli_query($con,$insertNews);
if($updateNews){
echo "<script>alert('Article updated.');</script>";
}
}
?>
You say $var_value is being passed to your php update script, but I cannot see that is is, nor is it being picked up by a POST and transferred to a local variable. Pass it as a <input type="hidden" and then pick up with a POST to use.
In first php script:
<p>Article Title<br /><input type='text' value='$newsTitle' name='newsTitle' />
<input type="hidden" value='$var_value' name='var_value' />
</p>
In second php script:
$var_value = $_POST['var_value'];
It would also be good to look at protecting your script from sql injection by using a parameterized query.
There is a problem with your query
insertNews = "UPDATE mods SET title='$newsTitle' date='$newsDate' shortBio='$newsShort' longBio='$newsLong' longBio2='$newsLong2' image='$newsImage' WHERE articleID='$var_value'";
Replace this with your current Query you will be good to go.

Multiple SQL Queries Into Multiple Arrays

I have this page thats a quick over view of the logged on users profile, along with some editing functions, so to avoid confusion I'm going to post all of the code, just ignore the html.
In the start of the code I'm retrieving the users information, and then storing it into an array called $row. Later on down the code, I'm retrieving rows from a seperate table, and I want to store those into an array aswell ($postRow). But I just figured out through reading that you can only preform one SQL query per page without running code that I, quite frankily don't understand, and the only tidbits of code that I found regarding that issue printed the information directly onto the page, I couldn't find any on how to store them both into arrays. Can someone help me regarding this issue? I'm really between a rock and a hard place.
<?php
include('header.php');
if (isset($_SESSION['username'])){
require 'connect.php';
$user = $_SESSION['username'];
$query = mysqli_query($connect, "SELECT * FROM users WHERE username='$user';", MYSQLI_USE_RESULT);
$row = mysqli_fetch_assoc($query);
?>
<h4>BlogHub > Profile > <?php echo $row['fname']." ".$row['lname']; ?></h4>
<div id="profileAva">
<img src="<?php echo $row['avatar']; ?>" />
</div>
<h5 id="infoDisp" style="margin:3px;"><?php echo "ID #".$row['ID']." - ".$row['fname']." ".$row['lname']." - ".$row['username']." - ".$row['email']." - ".$row['posts']." Posts"; ?></h5>
<?php
$id = $row['ID'];
$recentPost = mysqli_query($connect, "
SELECT *
FROM `blog_posts`
WHERE poster_id='$id'
LIMIT 1
", MYSQLI_USE_RESULT);
$postRow = mysqli_fetch_assoc($recentPost);
?>
<p></p>
<div id="changeAva">
<button class="cancelQuery">x</button>
<center>
<form style="padding-top:20px;" class="boxI" enctype="multipart/form-data" action="changeAva.php" method="POST">
<input style="padding-bottom:15px;" type="file" value="Choose a Avatar" name="file"/><br />
<button type="Submit">Submit</button>
</form>
</center>
</div>
<div id="changeInfoBox">
<button class="cancelQuery">x</button>
<center>
<form action="changeInfo.php" method="POST">
First Name: <input type="text" name="fname" value="<?php echo $row['fname']; ?>" /><br />
Last Name: <input type="text" name="lname" value="<?php echo $row['lname']; ?>" /><br />
Email: <input type="text" name="email" value="<?php echo $row['email']; ?>" /><br />
<button type="submit">Submit</button>
</form>
</center>
</div>
<?php
}
else {
echo "<center><p>You need to be logged in to view this page.</p></center>";
}
include('footer.php');
?>
There is no restriction on number of queries executed during a script execution. There is however no reason that you couldn't get this information in a single query. You would use a JOIN to do this.
This might look like this:
SELECT bp.*
FROM users AS u
INNER JOIN blog_posts AS bp
ON u.id = bp.poster_id
WHERE u.username = '?'
The particular problem you mention in comment to other answer is because you need to call mysql_free_result() before making your next query.

Editing HTML then posting via PHP

I have a scenario. Let's say someone is on my website and there is a form which adds an event for example and there is a field as follows:
<input type="text" name="title" id="title">
Let's say that person used F12 developer tools and changes the id="title" to id="whatever", or even remove the id attribute, then how would I make my PHP script stop running so that nothing is posted to MySQL?
Here's an example for a Bookmarks feature I have: (front-end form)
<form action="bookmarks.php" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="input-mini">Title*</label>
<div class="controls">
<input class="span12" id="title" name="title" type="text" placeholder="e.g. Oliver's pet cat...">
</div>
</div><!-- /control-group -->
<div class="control-group">
<label class="control-label" for="input-mini">Link*</label>
<div class="controls">
<input class="span12" id="link" name="link" type="text" placeholder="e.g. http://boopeo.com">
<input type="hidden" name="parse_var" id="parse_var" value="addbookmark" />
<br /><input name="submit" type="submit" class="btn btn-success span12" value="Bookmark" /></form>
Back-end PHP:
if (isset($_POST['parse_var'])){
$parser = $_POST['parse_var'];
$parser = htmlspecialchars($parser);
if ($parser == "addbookmark"){
$title = $_POST['title'];
$title = htmlspecialchars($title);
$linkurl = $_POST['link'];
$linkurl = htmlspecialchars($linkurl);
$sqlrecentmark = $db->query("SELECT link_url FROM tablenamehere WHERE mem_id='$id' ORDER BY id DESC LIMIT 20");
while($row = $sqlrecentmark->fetch(PDO::FETCH_ASSOC)) {
$recent_link = $row["link_url"];
}
if ( $linkurl != $recent_link ){
$dataact = array( 'mem_id' => $id, 'title' => $title, 'link_url' => $linkurl );
$sqlactivity = $db->prepare("INSERT INTO tablenamehere (mem_id, title, link_url) value (:mem_id, :title, :link_url)");
$sqlactivity->execute($dataact);
} else {
$not_msg = '<br /><br /><div class="alert alert-error">Oops! You have added that bookmark before. Just look and you shall find!</div>';
}
}
}
Never trust data from the user. Always sanitize and validate. You are using prepared statements which is good, so you'll be mostly protected from injection. The other thing you'll want to do is determine if the data the user has sent you matches up with what you were expecting, if it does then proceed to use it with the database. (Which you are for the most part doing, so in all honesty there should be no bad effects from a malicious user)
The id of input field doesn't get passed as posted data, so there's no way to tell in the back-end php code. Maybe you're talking about the name attribute.
<input type="text" name="theTitle" id="aTitle">
In my above example, the input field will be posted as $_POST["theTitle"]
You could use javascript to check these elements before the form is submitted, but if you're worried about the user manipulating the DOM, that probably won't help much.
After reading your concern about the Undefined index error, you simply need to check if the variable is set before you use it:
if(isset($_POST["title"])) {
$title = $_POST['title'];
} else {
//output error
}

PHP update on database failing - no errors [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I'm trying to update my database entries with this form:
<form method="post" action="inc/update.php">
<?php foreach ($links as $row) {
?>
<div class="btn_admin">
<p>
<label>Titulo</label>
<input type="text" name="title[]" value="<?php echo $row["desc"] ?>">
</p>
<p>
<label>Url</label>
<input type="text" name="url[]" value="<?php echo $row["url"] ?>">
<input type="hidden" name="id[]" value="<?php echo $row["id"] ?>" />
</p>
</div>
<?php }
?>
<input type="submit" name="submit" value="Update Links" />
</form>
On my update.php file:
if ($_SERVER["REQUEST_METHOD"] == "POST"
&& $_POST["submit"] == "Update Links") {
include_once 'db.php';
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
foreach($_POST['id'] as $id ) {
$title=$_POST["title"][$id-1];
$url=$_POST["url"][$id-1];
$sql = "UPATE index_links
SET desc=?, url=?
WHERE id=?";
$stmt = $db->prepare($sql);
$stmt->execute(array($title, $url, $id-1));
$stmt->closeCursor();
}
}
I've looped through $title and $url and everything is being 'grabbed' correctly, but the query is failing somehow with no errors.
I have even tried messing with erroneous query syntax (like in the query in the example above - "UPATE"), no errors whatsoever... and yes, the foreach loop is being accessed.
This seems like such intro level stuff, but I'm looking at this for an hour or so no and mind=blown... there are other queries (not UPDATE ones) on my project which are working fine.
In your case, the query probably fails because desc is a reserved word in mySQL.
PDO can be very secretive about its error messages by default. See this question on how to change that.

How to get ID from another file in php?

I'm going to make edit menu in my web. so I direct the page from product into edit page. What I'm confused is how to get the productID from product's page to use in edit page?
Here is my code in product
<?php $query= "SELECT * FROM game";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<div class="gameBox">
<div style="margin:5px;">
<?php echo "<image src=\"images/".$data['gameId'].".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <?php echo $data['gameName'];?></div>
<div class="myLabel">Developer</div><div>: <?php echo $data['gameDeveloper']; ?></div>
<div class="myLabel">Price</div><div>: $ <?php echo $data['gamePrice']; ?></div>
<br />
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
<input type="button" value="Delete"/>
</div>
</div>
<?php } ?>
and it's my code in edit page
<?php include("connect.php");
$id[0] = $_REQUEST['id'];
$query = "SELECT * FROM game WHERE gameId=".$id."";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<form action="doUpdate.php" method="post">
<?php echo "<image src=\"images/".$id.".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <input type="text" value="<?php echo $data['gameName'];?>" id="gameName" name="gameName"/></div>
<div class="myLabel">Developer</div><div>: <input type="text" value="<?php echo $data['gameDeveloper'];?>" id="gameDeveloper" name="gameDeveloper"/></div>
<div class="myLabel">Price</div><div>: <input type="text" value="<?php echo $data['gamePrice'];?>" id="gamePrice" name="gamePrice"/></div>
<br/>
<div id="txtError">
<!--error message here-->
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/></span>
<?php } ?>
When I try to access edit page, there's an error it said
"Undefined index:$id[0] = $_REQUEST['id'];"
in edit page.
Could anyone help me?
It looks like you're confusing two methods of passing data between pages, forms and query strings in <a href...>s.
Forms:
Data is in <input>-type elements (or friends) and inside a <form...> tag.
For example
<form action="handler.php">
<input type="text" name="var1" />
<input type="text" name="var2" />
<input type="submit">
</form>
Usually passed via POST and accessed in PHP via $_POST.
For example, the values in the text boxes referenced above would be accessed with something like:
<?php
echo $_POST['var1']; // First text box
echo $_POST['var2']; // Second text box
Links:
Passed as query strings in <a href...>, for example:
Click Me
Usually passed via GET and accessed in PHP via $_GET.
For example, the values in the query string provided above would be accessed with something like
<?php
echo $_GET['var1']; // "foo"
echo $_GET['var2']; // "bar"
So in this case it looks like you're hyperlinking an input button -- which is not the usual way to do things, but you would fix it by changing this:
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
To, this
<input type="button" value="Edit"/>
And then reference the variable in edit.php as $_GET['id'].
But since you know it's going to be an integer and nothing else, something like:
$id = (int)$_GET['id'];
Is good enough sanitation (at least for that variable).
Lastly, I notice you assign a variable to $id[0] but then reference $id. Assigning a variable to $id[0] is not the same as assigning it to $id, as $id is an array in the former and an integer in the latter. It seems to me that you can just drop the [0] w.r.t. $id in your edit.php
You can pass through the query string
<a href="edit.php?<?php $id=$data['gameId'];?>>
In this case your PHP code will get change to
$id[0] = $_SERVER['QUERY_STRING'];
Add the id as a parameter to your edit url:
<input type="button" value="Edit"/>
also at the top of your edit.php:
$id = $_REQUEST['id'];

Categories