I'm running into an issue while using the Update syntax when updating a table row with a string. I'll post the code below then explain my issue:
$query = "SELECT * FROM foo WHERE bar = '$id'";
$results = mysql_query($query);
$rows = mysql_num_rows($results);
for ($j = 0 ; $j < $rows ; ++$j) {
$entity_id=mysql_result($results,$j,'entity_id');
}
//$entity_id = "129";
if ($_POST['submit']) {
$text = mysql_real_escape_string($_POST['comments']);
$query = "UPDATE field_data_body SET body_value='$text' WHERE entity_id='$entity_id'";
mysql_query($query) or die ('Error updating database' . mysql_error());
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea name="comments">Example Comment</textarea>
<input name="submit" type="submit" value="submit" />
</form>
Here's a quick rundown of what the code does. I first request for the value of $entity_id from the table foo. I then update a different table row using a text-area and submit button.
My issue lies on line 12:
$query = "UPDATE field_data_body SET body_value='$text' WHERE entity_id='$entity_id'";
If $entity_id is passed directly to this line, the row will not update. If I assign an integer to $entity_id, (line 8 without the comment), the row will update. I've checked to make sure $entity_id is assigned a value before it gets to the submit section of the script; it returns 129, (echo "$entity_id"; output is 129). Why can I not pass the string without having to assign an integer?
EDIT: I found where the issue was taking place. The issue was on line 18, where the action attribute is called. I removed the php, and replaced it with a #. I'm not entirely sure why this was a fix to the problem, but there you have it. Thanks to those below with their suggestions and help, I do appreciate it!
Related
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've ran into a wall at the moment, This code brings up a table with a button on the end of each record. Once pressed this then does a function to UPDATE the Health record by -5.
This works great for the job but it effects all rows, I've tried to get it to only touched one record via the ID but no luck! if you can help that would be great!
the php
$sql="SELECT `id` , `FirstName` , `Health` FROM ajax_demo WHERE `id` = `id` LIMIT 0 , 30";
$result = mysql_query($sql);
if(isset($_REQUEST['submit']))
{
counterminus();
}
function counterminus()
{
$cmeter = $cmeter - 1;
$id = $_POST["id"];
$FirstName = $_POST["FirstName"];
mysql_query("UPDATE ajax_demo SET `Health` = `Health` - `Damage` WHERE id = {$id}");
Header("location:oo_test.php");
}
This is the php / form
<?php
echo
"<table border='1'>
<tr>
<th>id</th>
<th>Firstname</th>
<th>health</th>
</tr>";
while($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach($row as $cell) {
echo "\n<td>$cell</td>";
}
echo '<td><form id="theForm" action="" method="POST" >
<input type="submit" name="submit" id="submit" value="Attack" />
<input type="hidden" name="'.$row[1].'" /></form></td></tr>';
echo "\n\n";
}?>
This is vunerable to attack through the $_POST['id'] variable. Use mysql_real_escape_string, or better, prepared queries through PDO or MySQLi, anyway this is orthogonal to the issue you are having, it's just a good idea to be aware of it.
You're never actually submitting a HTML form field with the name id. In addition, in your HTML, $row will be NULL outside of your while loop, so will be undefined in the first place. This will mean that the name of your hidden field will be blank, and that your SQL is saying UPDATE WHERE id=, which is invalid and will cause an error.
To fix, you need to submit a form field with the name "id" such that $_POST['id'] actually contains a value.
Why did you write {id} instead of $id ?
Plus your code is totally unsafe and could be easily altered and hacked.
You should try PDO instead of mysql_query which is also depreciated.
http://php.net/PDO
I have an html form, with 13 <input> fields and approx. 92 different rows, created using php which pulls the records from a mySQL database. For some reason when I have a name assigned to this one field, it causes my <input type="submit" name="update_submit"> button not to set. If I change the name, it doesn't matter, but if I remove the name it will allow the other fields to update just fine.
Here is a snippet of my form code( $i is auto incremented):
Up Top...
<form method="post" action="process_form.php">
<table>
<tr>
Further down...
echo "<td align=\"center\" class=\"edit_emp_comp_exp_cell\"><input type=\"text\" maxlength=\"10\" size=\"10\" id=\"Lic_Comp_Exp$i\" name=\"Lic_Comp_Exp[]\" value=\"" . $emp_query['Lic_Comp_Exp'] . "\">";
<input type="submit" name="update_submit" style="width:100px;" value="UPDATE">
Further down...
</tr>
</table>
</form>
Here is my process_form:
if(isset($_POST['update_submit']))
{
$id = $_POST['Emp_ID'];
$name = $_POST['Emp_Name'];
$phone = $_POST['Emp_Phone'];
$start = $_POST['Start_Date'];
$leave = $_POST['Paid_Leave'];
$aca = $_POST['Emp_ACA'];
$licauth = $_POST['Lic_Auth_ID'];
$authexp = $_POST['Lic_Auth_Exp'];
$liccomp = $_POST['Lic_Comp_ID'];
$compexp = $_POST['Lic_Comp_Exp'];
$miscp = $_POST['MiscP_ID'];
$position = $_POST['Pos_ID'];
$active = $_POST['activeBox'];
$i = 0;
foreach($id as $update)
{
if (!isset($active[$i])) { $active[$i] = 0; }
$sql = ("UPDATE employee SET Emp_Name = '$name[$i]', Emp_Phone = '$phone[$i]', Emp_Start_Date = '$start[$i]', Paid_Leave = '$leave[$i]', Emp_ACA = '$aca[$i]', Lic_Auth_ID = '$licauth[$i]', Lic_Auth_Exp = '$authexp[$i]', Lic_Comp_ID = '$liccomp[$i]', Lic_Comp_Exp = '$compexp[$i]', MiscP_ID = '$miscp[$i]', Pos_ID = '$position[$i]', Emp_Active = '$active[$i]' WHERE Emp_ID = '$update'");
echo "SQL: " . $sql . "<br>";
if(!$result_employee_update = $mysqli->query($sql))
{
$errors[] = "There was an error updating the employee table. MySqli Error Number: " . $mysqli->errno . "";
goto end;
}
$i++;
}
goto redirect;
}
I am at a total loss and have been troubleshooting this all morning, I would really appreciate some help.
UPDATE: When I change if(isset($_POST['update_submit'])) to if(!isset($_POST['update_submit'])) and run it, I get an error:
"Notice: Undefined offset: 83 ... on line 31"
and line 31 is my
`$sql = ("UPDATE employee SET Emp_Name = '$name[$i]', Emp_Phone = '$phone[$i]', Emp_Start_Date = '$start[$i]', Paid_Leave = '$leave[$i]', Emp_ACA = '$aca[$i]', Lic_Auth_ID = '$licauth[$i]', Lic_Auth_Exp = '$authexp[$i]', Lic_Comp_ID = '$liccomp[$i]', Lic_Comp_Exp = '$compexp[$i]', MiscP_ID = '$miscp[$i]', Pos_ID = '$position[$i]', Emp_Active = '$active[$i]' WHERE Emp_ID = '$update'");`
I think that means that one of my <input> is not an array, right? If that is so, I don't know how that can be, the table is there and its created dynamically from the database.
UPDATE2: I think I've got something figured out, but I don't know how to fix it. I tried leaving the name="Lic_Auth_Exp" and name="Lic_Comp_Exp" and then removing two different name attributes from other input fields. After doing that it seemed to run the code. So the problem isn't because of these specific fields, but it seems to be because of there being more than 11 $_POST values being passed. I looked through the php.ini file to see if there were any limits on such a thing, but I didn't see anything. Does anyone know what could be causing this??
dump $_POST in php to check is it what you expect.
validate form structure. does all inputs are inside same tag?
Extend the condition
if(isset($_POST['update_submit']) && $_POST['update_submit']=="you-given-name-just-null")
I bet I've spent well in excess of 14 hours troubleshooting this problem, and #angel was kind enough to try in depth as well. FINALLY I have it figured out.
The problem ended up being the max_input_vars not being set high enough in my php.ini file. Even bigger problem was that the setting doesn't actually exist until you add it, so when you look through the file, you don't see anything setting a limit in the first place!!
So, to recap. The issue wasn't because of the name="" attribute like I was lead to believe. I figured this out when I removed two other names from two different input fields, suddenly it worked fine and it was only when I had these extra fields that it wouldn't work. The next clue came thanks to #Jakub Sacha when he suggested to use the var_dump($_POST) function. When I started looking at the numbers, it finally clicked that the total amount of fields being passed added up to 1000. After a Google search for PHP 1000 Limit I found out about this max_input_vars setting.
Hopefully this will help someone else out and prevent hours of troubleshooting!
I have the following query that I ran on my database to remove some data:
delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;
But I now need to make the a php function that runs when I press a button called clean
then print out all the subscriber data that was deleted.
Not quitesure where to start with this.
this is my html so far:
<form id="form1" name="form1" method="post" action="">
Clean subscribers:
<input type="submit" name="clean" id="clean" value="Clean" />
</form>
Any help or advice with this is very much appreciated.
C
You'll need the button to submit a form to a handler page, the handler page would then run the query, and collect+print the data.
If you don't want to refresh the page (or have your users diverted into another page), you'll want to use Ajax.
That's where you start.
Is abvious you made no effort! but I will answer you anyway.
<?php
$con = mysql_connect("serverUrl","login","password");
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM subscriber, subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
while($row = mysql_fetch_array($result))
{
echo $row['subscriber.name']; //assuming you have a field {name} in your table
echo "<br />";
}
mysql_query("delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
?>
First you'll need to select the data you're about to delete.
Then you'll need to delete it and return the selected rows.
$rows = array();
mysql_connect(...);
$res = mysql_query(...select query here...);
while($row=mysql_fetch_assoc($res)) {
$rows[] = $row;
}
$res = mysql_query(...delete query here...);
return $rows;
You might not want to totally delete the subscriber. If I were you I would include a field named "deleted" or something along those lines, indicating whether or not the subscriber has been deleted. Then query according to whether or not that field is true or false.
This is a continuation of the discussion at
PHP Multiple Dropdown Box Form Submit To MySQL
which ended with the words: "Once you have the variables, it is trivial to create new rows." No doubt that's generally true, but apparently not for this learner... :-D
Given the following form:
<form action="form.php" method="POST">
<select name="colors[]" multiple="yes" size="2">
<option>Red</option>
<option>Blue</option>
</select>
<input type="submit" value="Go!">
</form>
how do I create new rows? The following script
foreach($_POST['colors[]'] as $color)
{
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
}
raises the error
Warning: Invalid argument supplied for foreach() in form.php on line ...
whereas the following
$colors = $_POST['colors[]'];
for ($i = 0; $i < count($colors); $i++)
{
$color = $colors[$i];
$sql = "INSERT INTO colors SET id = '$color'";
}
raises no errors but does no row creation.
What triviality am I missing here?
Use:
foreach($_POST['colors'] as $color)
No need to specify [] here, php knows that it is an array.
Inside of your foreach loop I did not see that you are executing the query. You need to execute mysql_query with your INSERT statement.
foreach($_POST['colors'] as $color) {
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
if (!mysql_query($sql)) { // if the query encountered a problem.
die('Invalid query: ' . mysql_error());
}
}