Hi I have a html form button called delete. Next to the button is an input area. The logged in user will enter a number corresponding to the ID then press delete. It should delete the row corresponding to that ID.
For some reason it doesn't work.
This is my html form:
<h3 class="block-head">Delete Job</h3>
<form action="deletejob.php" method="post" class="basic-grey">
<label>Please Enter Job ID</label><input type="text" name="idnum" id="id"/><br>
<input type="submit" name="delete" value="delete"/>
</form>
This is my php code:
mysql_connect("********", "root", "******")
or die("Connection Failed");
mysql_select_db("jobslist")or die("Connection Failed");
$idnum = $_POST['id'];
$query = "delete from jobs_list where idnum = '".$id."'";
if(mysql_query($query)){ echo "deleted";}
else{ echo "fail";}
I know about switching to mysqli and that...I just want to see if this method works first.
thanks.
the name of your input is idnum yet you are looking in the $_POST array for id and in your query using the variable $id when you declare $idnum in the line previous.
$idnum = intval($_POST['idnum']);
$query = "delete from jobs_list where idnum = '".$idnum."'";
PHP receive the data via $_POST as an array of input elements with the key as the NAME of the input field, so you have to change this line:
$idnum = $_POST['idnum'];
You can also change the input name and don't change the php code:
<input type="text" name="id" id="id"/>
It's a typical mistake, don't worry too much about that :P
You should change the POST value.. and then try
$idnum = $_POST['idnum'];
Change the HTML, update the input type id to:
id="idnum"
then, update the PHP query while fetching the post value to:
$idnum = $_POST['idnum'];
It should work.
Related
So, I have a form with some field in my page. For example - auth.php. The data in fields of this form recieved by calling some php function, that gives this data from MySQL DB. The code:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
The data inserting in fields by this code:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
But how to realize mechanism of insertion some entry to my MySQL DB. For example, user pressed the ADD button on my Form, fill the field "Name" by his own data and press SAVE button - i want to save this user data directly in my MySQL DB.
Please help!
To achieve this, you'll need to follow a few steps:
create the html form
form.html
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
create submit page
submit.php
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
Now you should be able to have your data in database.
Please have a look at this example on how to connect to database http://docs.kisphp.net/database-connect/
Instead of mysqli you may/should use PDO.
P.S.
In your code:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
Is always a good practice to follow some principles:
function names starts with lowercase
class names starts with uppercase
do not use ?> in php files that contains only PHP code
indentation of all code is not necessary.
and so on.
you may find here more details http://www.php-fig.org/psr/psr-2/
P.P.S.
This is basic usage. Once you understand the principle you can extend it to ajax. Create an ajax function that will submit the form data to submit.php file.
I've a database it is look like this
|ID | Name |
|081| John Davidson|
and i have "index.php" in my website, i've learnt about php form, using method get, and the url is change to index.php?id=081
<form action="index.php" method="get">
<input name="id" value="081"/>
<input type="submit" value="Submit"/></form>
and when the page is loaded i want to show the name of id 081 from my database, how to do that?
Try this,
//Your index.php file
if($_GET['id']){
$id = $_GET['id'];
$sql="SELECT * FROM tableName where id='$id'";
$data = mysql_query($sql);
$row = mysql_fetch_array($data);
echo $row['name'];
}
<form action="index.php" method="get">
<input name="id" value="081"/>
<input type="submit" value="Submit"/></form>
After submitting , you are sending the id value with GET to index.php by url.
You can catch it with $_GET['id'],and store it in database like this:
$sql="INSERT INTO table SET id='".$_GET['id']."'";
$query=mysqli_query($connection,$sql);
If you want to retrieve this value from the database,you can do it like this:
$sql="SELECT id FROM table";
$query=mysqli_query($connection,$sql);
$row=mysqli_fetch_array($query);
echo $row['id'];
UPDATE As Abhik mentioned, those statements are very vulnerable, you should probably learn about using prepared statements here
Another simple way of avoiding sql injection , since it's pretty obvious you are new to php , is to use POST method instead of GET , and check on user input with this little function:
function test_input($data){
$data=htmlentities($data);
$data=stripslashes($data);
$data=trim($data);
return $data;
}
$id=test_input($_POST['id']);
Of course,depending on the field type, there must be some validation like min,max length , character allowed , etc.
$user_name = "xxx";
$password = "xxx";
$database = "xxx";
$server = "xxx";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$randWordDesc = mysql_query("SELECT * FROM words ORDER BY RAND() LIMIT 1");
$db_field = mysql_fetch_assoc($randWordDesc);
if(isset($_POST['new'])){
$unaltered = $db_field['word'];
$noA = str_replace("a", "b", $unaltered);
}
if (isset($_POST['edit'])){
global $noA;
$noR = str_replace("r", "c", $unaltered);
}
?>
<form action="http://xxx" method="post" ><br><br>
<input type="submit" value="edit current" name = "edit" id="gobutton">   
<input type="submit" value="new" name = "new" id="gobutton">
</form>
The code I have now will pull up a new word if the 'new' button is selected and replace the 'a''s with 'b''s. I want the 'edit' button to take the exact same word just pulled up and replace the 'r''s with 'c''s. However, as the code is now, the edit button will either pull up a new word or not pull up anything at all.
How could I get the edit button to edit the query that the 'new' button pulled up? I'm not sure how I could store it by the id, but all the columns have an id number, if that helps. Also I know that "SELECT * FROM words ORDER BY RAND() LIMIT 1" is really bad form, but that's an issue I want to tackle after this problem. Thanks for your help.
As the first query returns only one result, you could take the primary key column data of the resulting row and store it in a hidden input element on the page. When you use the edit button, you would then pass the hidden input field value which can be used to pull the same record as you pulled with the most recent get new word function call.
Consider something like the following:
<form action="http://xxx" method="post" ><br><br>
<input type="hidden" value=<?php echo $db_field['primary_key']; ?> name="record_id">
<input type="submit" value="edit current" name = "edit" id="gobutton">   
<input type="submit" value="new" name = "new" id="gobutton">
</form>
The id will be passed with your post, which you can then check for and use in a select query to get the record. Just be sure to be careful with data handling. Consider updating to a current API (mysql~ functions are deprecated) and prepared statements.
HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.
I am new to PHP and working on small local webpage and database that takes user information and database stores the same user information .If i Login with ADMIN it shows all data. My requirement is that the loggined user is an admin, then he has a right to edit all the informtion of the users that i stored in the database.And this is to be done using GET method . How it will be working?
Heres some example code purely to demonstrate how to update a table using a GET method form. The code doesn't have any kind of error checking and assumes you already know how to connect to your database (and that its MySQL).
Assuming you've landed on a page which invites you to edit data, which record you're editing is referenced by an 'id' variable on the URL which matches a numerical primary key in your database table.
<?php
$SQL = "SELECT myField1,myField2 FROM myTable WHERE myKeyField = '".intval($_GET['id'])."'";
$QRY = mysql_query($SQL);
$DATA = mysql_fetch_assoc($QRY);
?>
<form method='get' action='pageThatStoresData.php'>
<input type='hidden' name='key' value='<?php echo $_GET['id']; ?>' />
<input type='text' name='myField1' value="<?php echo $DATA['myField1']; ?>" />
<input type='text' name='myField2' value="<?php echo $DATA['myField2']; ?>" />
<button type='submit'>Submit</button>
</form>
So, this will give you a page that takes the data out of your table, displays it in a form with pre-filled values and on submit, will go to a URL like:
http://mydomain.com/pageThatStoresData.php?key=1&myField1=someData&myField2=someMoreData
In that page, you can access variables 'key', 'myField1', 'myField2' via the $_GET method.
Then you just need to update your table within that page:
$SQL = "UPDATE myTable
SET myField1 = '".mysql_real_escape_string($_GET['myField1'])."',
myField2 = ".mysql_real_escape_string($_GET['myField1'])."
WHERE key = '".intval($_GET['key'])."'
";
$QRY = mysql_query($SQL);
PLEASE NOTE: The code above is unsuitable for a straight copy/paste as it doesn't do any error checking etc, its purely a functional example (and typed straight in here so I apologise if there are any typos!).