This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
PHP UPDATE prepared statement
(3 answers)
Closed 11 months ago.
Can anybody help me understand why this update query isn't updating the fields in my database? I have this in my php page to retrieve the current values from the database:
<?php
$query = mysql_query ("SELECT * FROM blogEntry WHERE username = 'bobjones' ORDER BY id DESC");
while ($row = mysql_fetch_array ($query))
{
$id = $row['id'];
$username = $row['username'];
$title = $row['title'];
$date = $row['date'];
$category = $row['category'];
$content = $row['content'];
?>
Here i my HTML Form:
<form method="post" action="editblogscript.php">
ID: <input type="text" name="id" value="<?php echo $id; ?>" /><br />
Username: <input type="text" name="username" value="<?php echo $_SESSION['username']; ?>" /><br />
Title: <input type="text" name="udtitle" value="<?php echo $title; ?>"/><br />
Date: <input type="text" name="date" value="<?php echo $date; ?>"/><br />
Message: <textarea name = "udcontent" cols="45" rows="5"><?php echo $content; ?></textarea><br />
<input type= "submit" name = "edit" value="Edit!">
</form>
and here is my 'editblogscript':
<?php
mysql_connect ("localhost", "root", "");
mysql_select_db("blogass");
if (isset($_POST['edit'])) {
$id = $_POST['id'];
$udtitle = $_POST['udtitle'];
$udcontent = $_POST['udcontent'];
mysql_query("UPDATE blogEntry SET content = $udcontent, title = $udtitle WHERE id = $id");
}
header( 'Location: index.php' ) ;
?>
I don't understand why it doesn't work.
You have to have single quotes around any VARCHAR content in your queries. So your update query should be:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");
Also, it is bad form to update your database directly with the content from a POST. You should sanitize your incoming data with the mysql_real_escape_string function.
Need to add quote for that need to use dot operator:
mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");
Without knowing what the actual error you are getting is I would guess it is missing quotes. try the following:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = '$id'")
Here i updated two variables and present date and time
$id = "1";
$title = "phpmyadmin";
$sql= mysql_query("UPDATE table_name SET id ='".$id."', title = '".$title."',now() WHERE id = '".$id."' ");
now() function update current date and time.
note: For update query we have define the particular id otherwise it update whole table defaulty
First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.
Try like this in sql query, It will work fine.
$sql="UPDATE create_test set url= '$_POST[url]' WHERE test_name='$test_name';";
If you have to update multiple columns,
Use like this,
$sql="UPDATE create_test set `url`= '$_POST[url]',`platform`='$_POST[platform]' WHERE test_name='$test_name';";
you must write single quotes then double quotes then dot before name of field and after like that
mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");
Related
I'm currently doing a project for my class project. I'm currently trying to update into the database but I get some errors along the way basically it's a radio button to setup to link to a update page. Any help and insights would be appreciated!
<html>
<head>
<title>asdf</title>
<link rel="stylesheet" type="text/css" href="Background.css">
</head>
<?php
session_start();
if(!isset($_SESSION["login"]))
header("location:admin.php");
?>
<body>
<h1 style="color:white"><u><center></center></u></h1>
<div id="BG"></div>
<form action = "update1.php" method = "GET">
<table border = 0>
<tr>
<td>Image: <input type = "text" name = "image" id = "image"></td>
<br/>
<td>Hero Name: <input type = "text" name = "heroes" id = "heroes"></td>
<br/>
<td>Role: <input type = "text" name = "roles" id = "roles"></td>
<br/>
<td>Attribute: <input type = "text" name = "attribute" id = "attribute"></td>
<br/>
<td>Description: <input type = "text" name = "description" id = "description"></td>
<br/>
<td>General: <input type = "text" name = "general" id = "general"></td>
<br/>
</tr>
</table>
</br>
<input type = "submit" name="update" value = "Update">
</form>
</center>
</html>
<?php
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
define("DB_USER","*****");
define("DB_PASSWORD","****");
define("DB_HOST","*****");
define("DB_NAME","*****");
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
if(isset($_GET['update']))
{
$image = $_GET['image'];
$heroes = $_GET['heroes'];
$roles = $_GET['roles'];
$attribute = $_GET['attribute'];
$description = $_GET['description'];
$general = $_GET['general'];
$sql = "update `Dota 2 select` set (`image` = '$image',`heroes` = '$heroes') WHERE (heroes= '$heroes', image = '$image')";
// $sql = "Update `Dota 2 select` SET (`image`= [$image]) = WHERE `image`)";
// $sql = "Update `Dota 2 select` SET (`image`= [$image],`heroes` =[$heroes],`roles` =[$roles],`attribute`=[$attribute],`description`=[$description],`general`=[$general]) = WHERE `heroes`='$heroes')";
// $sql = "Update `Dota 2 select` SET (`image`= [$image],`heroes`,`roles`,`attribute`,`description`,`general`) = WHERE (`image`,`heroes`,`roles`,`attribute`,`description`,`general`) = ('$image','$heroes','$roles','$attribute','$description','$general')";
if(!mysqli_query($dbc, $sql))
{
echo(mysqli_error($dbc));
}
else
{
echo 'Data successfully updated!';
}
mysqli_close($dbc);
}
?>
This is the error for this page
"
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(image = 'a',heroes = 'a') WHERE (heroes= 'a', image = 'a')' at line 1
"
Seems you are getting MySQL insert and update syntax mixed..
UPDATE `table` set `col1`='val1', `col2`='val2',....
which when set as a PHP var might look like
$sql = 'UPDATE `table` set `col1`=\''. $val1.'\', `col2`=\''.$val2.'\',....
More than one way to do that, but this is my preferred way. backticks around column names, and escaped apostrophes around values, since I use single quote strings here
The table name has invalid space !
You can set your instruction as :
"update Dota_2_select set image = $image , heroes = $heroes where heroes= $heroes, image = $image";
Removing the spaces between table name and using " instead of ' because you can call de php variables $ directly .
Your first where is wrong:
WHERE (heroes= '$heroes', image = '$image')";
It should be
WHERE (heroes= '$heroes' AND image = '$image')";
^^^^
You are also vulnerable to sql injection attacks
Your second one fails because you test for the existence of your $_GET value AFTER you already tried using it:
if (isset($_GET['Heroes'])) {
$Heroes = $_GET['heroes'];
...
}
room.php
<input name = "room" type = "text" size="70"/>
Update
updateroom.php
<?php
mysql_connect('localhost','athirahhazira','1234');
mysql_select_db("dbcollege");
session_start();
$sql = "UPDATE studentsroom set room='$strroom' WHERE roomid='$_GET[roomid]'";
mysql_query($sql) or die('Error updating room status');
header('Location:staff/room-staff.php');
?>
i can update if there is a default value such as :
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='$_GET[roomid]'";
but not the value from a textbox. could u help me with what i am missing here?
try this
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='".$_REQUEST['roomid']."'";
Note: your code can be sql injection. also mysql_* is deprecated use mysqli_* or PDO
Update2:
add a form and submit button instead of hyperlink
<form method="post" action="updateroom.php" >
<input name = "room" type = "text" size="70"/>
<input type="hidden" name="roomid" value="<?php echo $row_Recordsetroomid['roomid'];?>" />
<input type="submit" name="submit" value="Update" />
</form>
AND update.php
<?php
mysql_connect('localhost','athirahhazira','1234');
mysql_select_db("dbcollege");
session_start();
$room = $_REQUEST['room'];
$roomid = $_REQUEST['roomid'];
$room = mysql_real_escape_string($room);
$roomid = mysql_real_escape_string($roomid);
$sql = "UPDATE studentsroom set room='$room' WHERE roomid='$roomid'";
mysql_query($sql) or die('Error updating room status');
header('Location:staff/room-staff.php');
?>
The quotes for the index in the $_GET is missing. Trying to access array variables like $array[key] instead of $array['key'], will trigger an error in most cases. So always try to use quotes for array indexes.
You can try with this.
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='".$_GET['roomid']."'";
I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..
i have this code which permits me to do a request in order to make a query!
Now the form which is processed has this code:
<form action="edit_images.php" method="post">
<input type="hidden" value="<? echo $gal_id1 ?>" name="img_id1" />
<input type="submit" value="Edit All Images" />
</form>
While the query is like this :
$img_id=$_REQUEST['img_id1'];
$sql="SELECT * FROM tbl_images WHERE Img_gal_id='$img_id'";
But it seems like it won't take the value...
I mean, it doesn't recognize the $img_id, which i have printed before and takes the exact value.
Let me show you the query i use in order to retrieve it:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
if(isset($myErrors) && $myErrorsP!=''){
} else {
$row = mysql_fetch_row($query);
mysql_free_result($query);
$gal_id = $row[0];
$gal_id1 = $row[0];
$gal_title = $row[1];
$gal_image = $row[2];
}
You are missing a ; on the end of your echo that isn't outputting the value as expected. Additionally, you are using short tags, which could be causing problems. You might want to swtich to using <?php as an opening over <? on it's own.
<input type="hidden" value="<?php echo $gal_id1; ?>" name="img_id1" />
Lastly, you are using zero protection against injection attacks. Please, research prepared statements in PDO and update your code. The first injection attack you don't have will thank you for it.
Edit: When you run into a problem like this, it is often good practice to echo out the $sql just before you execute it.
you could do this in the future with:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
echo $sql."<br>\n";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
which would have probably given you an excellent indication of what the problem was.
I have a table that has the user ID already in it, but some of the information is missing and that is where I need the user to input it themselves. With the URL of the form I have their ID in it... winnerpage.php?ID=123
I am having troubles getting the code to work. Any help would be great!
This is the code on that winnerpage.php
<form enctype="multipart/form-data" action="winnerpage.php" method="POST">
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
First Name: <input type="text" name="FN"><br />
Last Name: <input type="text" name="LN"><br />
Email: <input type="text" name="EM"><br />
Phone: <input type="text" name="PH"><br />
<input type="submit" name="edit" value="edit"></form> <br>
<?
require_once('mysql_serv_inc.php');
$conn = mysql_connect("$mysql_server","$mysql_user","$mysql_pass");
if (!$conn) die ("ERROR");
mysql_select_db($mysql_database,$conn) or die ("ERROR");
if(isset($_POST['edit']))
{
$sID = addslashes($_POST['ID']);
$sFN = addslashes($_POST['FN']);
$sLN = addslashes($_POST['LN']);
$sEM = addslashes($_POST['EM']);
$sPH = addslashes($_POST['PH']);
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH
WHERE ID=$sID') or die (mysql_error());
echo 'Updated!';
}
$query = "select * from winner order by ID";
$result = mysql_query($query);
?>
<?
while ($link=mysql_fetch_array($result))
{
echo 'Unique ID - Completion Time - First Name - Last Name - Email - Phone<br/>'.$link[ID].' -' .$link[FN].' - '.$link[LN].' - '.$link[EM].' - '.$link[PH].'<br>';
}
?>
1)
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
Where do you get that $ID? Are you doing something like $_GET['ID'] or are you relying on safe_mode being ON? (it's not clear from the code you provided)
(better yet, if(isset($_GET['ID'])) { $ID = (int)$_GET['ID'] }
2) Please don't to that. Don't use addslashes(). Use mysql_real_escape_string() or, even better, prepared statements. Addslashes is not utterly reliable in escaping datas for queries.
sID = (int)$_POST['ID'];
$sFN = mysql_real_escape_string($_POST['FN']);
$sLN = mysql_real_escape_string($_POST['LN']);
$sEM = mysql_real_escape_string($_POST['EM']);
$sPH = mysql_real_escape_string($_POST['PH']);
Also, add 'value=""' to each input field (not mandatory)
3) encapsulate values in query:
mysql_query("UPDATE winner SET FN='".$sFN."', LN='".$sLN."', EM='".$sEM."', PH='".$sPH."' WHERE ID='".$sID."'") or die (mysql_error());
Maybe try:
mysql_query("UPDATE winner SET FN='$sFN', LN='$sLN', EM='$sEM', PH='$sPH' WHERE ID=$sID") or die (mysql_error());
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH WHERE ID=$sID')
the query is encapsulated by single-quotes, so the variables inside will not be parsed.
At first glance I would say that you need:
1) Quote marks around some of the values you are inserting into the table (any strings for example)
2) Quote marks around the names of the fields when you try to echo them out at the end ($link['ID'] for example)