basic edit.php won´t update the data - php

I have a small (42 hours) problem with my code trying to edit article
- just the basic editNews.php
When I choose article to edit the data appears in the forms from the DB and when
I hit "update" it returns no error but the data wasn´t updated
<?PHP
connection to database blah blah
?>
<?php
if(isset($_POST['update']))
{
$newsid = $_POST['newsid'];
$date=$_POST['date'];
$time=$_POST['time'];
$location=$_POST['location'];
$result=mysql_query("UPDATE news SET date='$date',time='$time',location='$location', WHERE newsid=$newsid");
header("Location: listNews.php");
}
}
?>
<?php
$newsid = $_GET['newsid'];
$result=mysql_query("select * from news where newsid=$newsid");
while($res=mysql_fetch_array($result))
{
$date = $res['date'];
$time = $res['time'];
$location = $res['location'];
}
?>
This is the form - just the normal one....
<form method="post" action="editNews.php" name="form1">
each item is like
<input type="text" name="headline" value="<?php echo $location;?>" id="UserName">
and
<input type="hidden" name="newsid" value=<?php echo $_GET['newsid'];?>
<input name="update" type="submit" value="update" />
Most likely there is something that I don´t see but "seeing" has taken almost 2 days now
... Is there a possibility I don´t have "edit" privileges in the mySql?

How do you know there was no error? Your code lacks:
print mysql_error();
Add it right after the UPDATE query.
Also your code is most likely to fail whenever the submitted content itself contains single quotes. To send correct SQL to the database it's advisable to apply mysql_real_escape_string() on all input variables.

Try
$result= mysql_query('UPDATE news SET
date = "'. $date .'",
time = "'. $time. '",
location = "' .$location. '"
WHERE newsid = '.$newsid.';') OR die(mysql_error());

Related

updating mysql through form data retains old values

I am battling with the below code. The below is intended to:
1) Read data course data from database
2) Display data in a form ready for editing
3) Once edited, on submit, pass edited values to database
The issue I am getting is that I am able to execute 1 and 2 with no issues, but when I pass the edit data to database in step 3, the old values which where presented in step one are instead passed. How to I get the edited values to be passed and not the old values?
Thank you in advance
$readQuery="SELECT * FROM course WHERE course_id={$id}";
$readResult=mysqli_query($connection, $readQuery);
validateQuery($readResult);
while($row=mysqli_fetch_assoc($readResult))
{
$courseId=$row["course_id"];
$courseName=$row["course_name"];
$courseDescr=$row["course_descr"];
$courseCost=$row["course_cost"];
$courseDuration=$row["course_duration"];
}
?>
<form action="course_man.php?page=<?php echo $page?>" &id=<?php echo $id?>" method="post">
<table>
<tr>
<td align="right">
<!--Course ID <input type="text" name="course_id" value="<?php //echo $courseId;?>"/><br/>-->
Course Name <input type="text" name="course_name" value="<?php echo $courseName;?>"/><br/>
Course Description <textarea name ="course_descr" rows="6" cols ="30" ><?php echo $courseDescr;?></textarea><br/>
Course Cost <input type="text" name="course_cost" value="<?php echo $courseCost;?>"/><br/>
Course Duration <input type="text" name="course_duration" value="<?php echo $courseDuration;?>"/><br/>
<input type="submit" name="update" value="Update"/>
</td>
</tr>
</table>
</form>
<?php
}
if(isset ($_POST['update']))
{
$updateQuery="UPDATE course SET ";
$updateQuery.="course_name='{$courseName}', ";
$updateQuery.="course_descr='{$courseDescr}', ";
$updateQuery.="course_cost={$courseCost}, ";
$updateQuery.="course_duration={$courseDuration}, ";
$updateQuery.="WHERE course_id={$id}";
$check = mysqli_query($connection, $updateQuery);
mysqli_error($connection);
}
Go through your code line-by-line. How is the script supposed to get the new values from the form? A sql query is executed in all cases and the variables such as $courseName are set with the old values anyway. Now, when we get to the updating part, variables are still set with old values.
if(isset ($_POST['update']))
{
$updateQuery="UPDATE course SET ";
$updateQuery.="course_name='". $_POST['course_name'] ."', ";
$updateQuery.="course_descr='". $_POST['course_descr'] ."', ";
$updateQuery.="course_cost=". $_POST['course_cost'] .", ";
$updateQuery.="course_duration=". $_POST['course_duration'] .", ";
$updateQuery.="WHERE course_id=". $_POST['course_id'];
$check = mysqli_query($connection, $updateQuery);
mysqli_error($connection);
}
Move this code up before SELECT... query. And do not forget to sanitize user data before putting it into the query! Use mysqli_real_escape_string() http://php.net/manual/en/mysqli.real-escape-string.php or something else.
When you submit form to course_man.php it again fetch data from db and your below variables will be overwritten with db values.
$courseId=$row["course_id"];
$courseName=$row["course_name"];
$courseDescr=$row["course_descr"];
$courseCost=$row["course_cost"];
$courseDuration=$row["course_duration"];
Try this ....
$updateQuery="UPDATE course SET course_name = '$courseName',
course_descr = '$courseDescr',
course_cost = '$courseCost',
course_duration = '$courseDuration'
WHERE course_id = $id
";

edit button to mysql

I got my database to work, and I can add my data and get return on it again. That is perfect, because it is the first time that I get it to work, and it opend up a lot of possibilies. So my next project here, is to ALTER my table in MySQL with a button. Until now it looks like this:
I can add a date, day, fromtime and totime. But I would like to have the possibility to change fx the day, if I make a mistake when I add the values to my database. I started on making an edit button in the right hand side. So overtime I make a new row, there will come a new edit button. But does anybody know how I can asign my button to the ALTER TABLE query? Or maybe a hint how to do it?
Best Regards to all
From Mads
EDITED CODE:
I have made the primary key in the database p_id. I also get a return from the p_id
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/arrangeTables.css">
</head>
<body>
<form method="post">
<h3>Add your worktime to database</h3><br>
<input type="date" name="date"><br><br>
<select name="day">
<option value="Mandag">Mandag</option>
<option value="Tirsdag">Tirsdag</option>
<option value="Onsdag">Onsdag</option>
<option value="Torsdag">Torsdag</option>
<option value="Fredag">Fredag</option>
<option value="Lørdag">Lørdag</option>
<option value="Søndag">Søndag</option>
</select>
<input type="time" name="fromtime">
<input type="time" name="totime">
<input type="submit" value="submit"><br><br>
</form>
</body>
<?php
$username = "root";
$password = "root";
$hostname = "127.0.0.1:3306";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br><br>";
//select a database to work with
$selected = mysql_select_db("danskebank",$dbhandle)
or die("Could not select any database");
// Insert to database
$date = $_POST['date'];
$day = $_POST['day'];
$fromtime = $_POST['fromtime'];
$totime = $_POST['totime'];
$sql = "INSERT INTO addWorkTime(date, day, fromtime, totime) VALUES('$date', '$day', '$fromtime', 'totime')";
$result = mysql_query($sql);
//Return records from database
$result = mysql_query("SELECT date, day, fromtime, totime FROM addWorkTime");
?>
<!-- Return from the database -->
<h3>Return from database:</h3><br>
<!-- headers -->
<tr>
<th class="column1">Date</th>
<th class="column2">Day</th>
<th class="column3">From</th>
<th class="column4">To</th>
</tr>
<!-- Now a row for each new set of data, here you probably need to
loop through some data set you retrieve from the database -->
<?php while($row = mysql_fetch_array($result)): ?>
<table>
<tr>
<td class="resultcolumn4"><?php echo $row{'p_id'};?></td>
<td class="resultcolumn1"><?php echo $row{'date'};?><br></td>
<td class="resultcolumn2"><?php echo $row{'day'};?></td>
<td class="resultcolumn3"><?php echo $row{'fromtime'};?></td>
<td class="resultcolumn4"><?php echo $row{'totime'};?></td>
<td><a href='link_to_the_add_or_edit?id='.<?php $row['id'] ?></td>
<?php
$id=$_GET['id'];
echo '<input type="hidden" name="name_of_hidden_input" value='.$id.'>';
//and the rest of the form
if($_GET['submit']){
//Some mysql injection prevention first
update danskebank SET date=['?'] where id= $_GET['name_of_hidden_input']
}
?>
</tr>
<?php endwhile; ?>
</table>
</html>
To edit the specific row, you would need a Primary key in your mysql table. For example you call it: id. Now you would need to get the id from the table as well: SELECT id, date, day, fromtime, totime FROM addWorkTime
Use the $row['id']; in the while loop and replace the : <input type="button" value="Edit"> to: <a href='link_to_the_add_or_edit?id='.<?php $row['id'] ?> now your url will look like: link_to_the_add_or_edit?id=1 and you can use: $_GET['id'] on the link_to_the_add_or_edit page. Now when you're on that page, you make sure you remember that id(SESSIONS) so you can use it on the submit action when you fill in the values.
Example of session:
session_start();
$_SESSION['id']=$_GET['id'];
on the link_to_the_add_or_edit page. After this you can update the row you want like this(when you submit something):
update danskebank SET date=['?'] where id= $_SESSION['id']
EDIT(regarding DarkBee's comment):
Instead of using sessions here, you can also store the $_GET['id'] in a hidden field like this:
$id=$_GET['id'];
echo '<input type="hidden" name="name_of_hidden_input" value='.$id.'>';
//and the rest of the form
if($_GET['submit']){
//Some mysql injection prevention first
update danskebank SET date=['?'] where id= $_GET['name_of_hidden_input']
}
and in the query use: $_GET['name_of_hidden_input'];
If you want to edit the values of the row try via url:
echo '<a href="edit.php?row_id=' . $row_id . '>Edit</a>'; //You should have id for every row
Create edit.php file and get row's id with $_GET['row_id']. Create form Add some input in it (like this one:<input type="datetime" />), and then handle it with another php file. You should execute your UPDATE query there. Like this :
$sql = "UPDATE row SET
date = '$date' ,
day = '$day' ,
fromtime = '$fromtime' ,
totime = '$totime'
WHERE id = $row_id;
";
mysql_query($sql);
But for all these you should have id for every row in the database.

UPDATE inside a WHILE statement

So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...

how can i view the data resulting from one of the choices in the dropdown list?

im new to php so im having some problems creating what i want
i'll explain first what i need .. there conferences, each conference has a list of reviewers and authors.
i have create a dropdown list where the user chooses which conference ... i want to show a list of the reviewers and the authors that are in this conference after clicking submit.
that is my code
<?php
$con = mysql_connect("localhost:3306","root","");
mysql_select_db("messaging_dd", $con);
$sql_drop = "SELECT conference_ID,conference_name FROM Conferences";
$drop_result = mysql_query($sql_drop,$con) or die(mysql_error());
$num_rows = mysql_num_rows($drop_result) or die(mysql_error());
mysql_close($con);
?>
<form name="choose" action="savedata.php" method="POST">
<br />
Conference: <select name="conference">
<?php
for($i=0 ; $i<$num_rows ; $i++)
{
$idofconference = mysql_result($drop_result,$i,0);
$nameofconference = mysql_result($drop_result,$i,1);
echo '<option value=" '.$idofconference.' ">'.$nameofconference.'</option>';
}
?>
</select>
<br />
<input type="submit" value="submit" name="submit" />
</form>
Try this,
$conf_id = $_POST['conference'];
$con = mysql_connect("localhost:3306","root","");
mysql_select_db("messaging_dd", $con);
$sql = "SELECT review, author FROM Reviews WHERE conf_id = ".$conf_id;
$review_list = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
Or you can go for Ajax. Updating your search result, without reloading the whole page. Reference for Ajax: http://www.w3schools.com/php/php_ajax_database.asp
All the data being submitted gets stored in the $_POST variable as an array. Your conference ID will be in $_POST['conference'] as the name of your select element is conference.
An other approach is to load the desired data (reviewers and authors) through an AJAX request so that the viewer of your website won't leave the webpage.
it's similar to what you have done, just add conference id details like this:
$sql = "SELECT reviewer, author FROM Conferences where conference_ID = " . $_POST['conference'];
In your file savedata.php you can put
$whatever = $_POST['conference']
$_POST is one of several arrays in php that is reserved for system data, for example you can make calls to $_server to find out details about the server(eg the time on the server)
you could also change the method='POST' to method='GET' and it would be in the GET array
$whatever = $_GET['conference']
this is a bit less secure, but if that's not a priority its worth considering
I think you should Try this.
<form name="choose" action="savedata.php" method="POST">
<br />
Conference: <select name="conference">
<?php
while($row=mysql_fetch_array($drop_result)
{
echo '<option value=" '.$idofconference.' ">'.$nameofconference.'</option>';
}
?>
</select>

MYSQL Update not updating database?

I have a simple Form along side a PHP update query that simply isn't working! I know the PHP is working on the page as there are several validation checks that need to be passed before hand which are working perfectly. The form its self is inside the Colorbox Popup tool.
My HTML Form Code is:
<div id="stylized" class="myform">
<form action="#" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
<label>First Name:<span class="small">Enter your forename</span></label>
<input id="first_name" type="text" name="first_name" maxlength="50" placeholder="e.g. Joe" required autofocus/>
<div class="spacer"></div>
<input type="submit" id="update" name="update" value="Continue to Step 2!">
</form>
</div>
With the PHP Code as follows (this is above the HTML code on the page):
<?php
if($_POST['update']){
$user_i = $_POST['user_id'];
$f_name = $_POST['first_name'];
$first_name = ucfirst($f_name);
mysql_query("UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'") or die(mysql_error());
} ?>
The actual submit appears to be working, with the Popup refreshing afterwards, but the database does not update! I have triple checked the syntax and the database fields. 'user' and 'first_name' and 'user_id' is correct.
Update: Because the popup box refreshes, I cannot view the error's from the 'or die(mysql_error()) unfortunately, other wise i might have been one step closer.
Any help would be hugely appreciated.
Many thanks in advance.
When you say pop-up box, I assume you are using ajax to communicate from the form to the server, which as you stated is difficult to view submitted data. If this is the case try:
error_log(serialize($_POST));
This will force an entry in your error log with the $_POST data in serialized format, so you can check the values you are submitting are populated correctly.
You will also want to sanitize the variables you are adding to the SQL:
$sql = "UPDATE user SET first_name = " . mysql_real_escape_string($first_name) . " WHERE user_id = " . mysql_real_escape_string($user_i) . " LIMIT 1";
mysql_query($sql);
I would:
print_r($_POST); to view the POST data.
Generate the SQL from a string so it can be printed for debugging purposes, like so:
$sql = "UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'";
echo $sql;
mysql_query($sql) or die(mysql_error());
One of these techniques will likely tell you why the PHP-generated SQL doesn't update your database record.
you set your user_id field by echo $user_id; but your variable name is set to $user_i = $_POST['user_id'];
therefore your user id field is not set and your Mysql command will fail.

Categories