Simple insert not working from form? - php

This won't work for me, I have been using inserts and every other sql statment there on this work, but for some reason this is not working.
The table below is structured as follows.
**passenger_journey**
j_id user_id
142 1
142 14
Below all I'm trying to do is insert the logged in users id which is the $user_id and the journey id which is $id. Thee are working are the variables are set.
I think a possible problem may be the $id as I'm getting this from the url using the GET method.
<?php
$insert_passenger = "INSERT INTO `passenger_journey` VALUES ('" . mysql_real_escape_string($id) ."','" . mysql_real_escape_string($user_id) . "')";
if (isset($_POST['submit'])){
mysql_query($insert_passenger);
}
?>
<form method="POST">
<br/>Add yourself to this journey!<br/>
<input type ="submit" value="Sign up for this Journey"/>
</form>
This has been driving me mad for hours any help would be great.

This doesn't match up:
<form method="POST">
<br/>Add yourself to this journey!<br/>
<input type ="submit" value="Sign up for this Journey"/>
</form>
And:
if (isset($_POST['submit'])){
mysql_query($insert_passenger);
}
You need to assign a name to your submit button for that if statement to be true:
<input type="submit" name="submit" value="Sign up for this Journey"/>
...and you'll need to pass those variables into the action of your form to be able to use them in the $_GET superglobal.
<?php
$your_id = // define your id here, I assume in your insert query this should just be null.
$user_id = // define your user id here however you're getting it... sessions...?
?>
<form method="POST" action="?id=<?=$your_id?>&user_id=<?=$user_id?>">
NOTE: if your id and user_id variables are coming from sessions, cookies etc or anything that can be retrieved in the script doing the insert, definitely do it there instead of passing it through an HTML form when you don't need to.
Usually when inserting data with MySQL, the relevant id column will be set to auto_increment, and you either wouldn't pass in a value for it or you'd pass in null so you let it assign its own value. You should probably be doing that here (although I don't know your situation at all):
$insert_passenger = "INSERT INTO `passenger_journey` VALUES (null,'" . mysql_real_escape_string($_GET['user_id']) . "')";
Side note: Not only is the fact that mysql* is deprecated going to cause you trouble, but this script is vulnerable to SQL injection and XSS.
Docs/more info:
http://php.net/manual/en/security.database.sql-injection.php
http://www.sitepoint.com/php-security-cross-site-scripting-attacks-xss/

Related

PHP Form isn't POSTing data to database

I made a simple form with two variables which should be sent to database after SUBMITing them. However even thought there is no bug reports, the database is still empty after submit. Where Can I look for mistake?
I already tried multiple ' or " or '", none of these worked. I can with no problem SELECT data from fdatabase so the connection is established.
$total = $_POST['kwota'];
$way = $_POST['sposob'];
echo $total . "<BR>" . $way;
$sql = "INSERT INTO payments (Total, Way) VALUES ('$kwota', '$sposob');";
mysqli_query($conn, $sql);
header("Location: ../index.php?Payment=success");
<form action="includes/Platnosc.inc.php" method="POST">
<input type="text" name="kwota" placeholder="kwota"><br>
<input type="text" name="sposob" placeholder="sposób"><br>
<button type="submit" name="submit">Dodaj płatność</button>
</form>
You are inserting $_POST array indexes as php variables. Change your query to this
$sql = "INSERT INTO payments (Total, Way) VALUES ('$total', '$way')";
However, I suggest you to use prepared statements to prevent from sql injections

Why aren't the values from my form inserting into the database?

I have the following form:
<form id ="classadderform" action="formsubmit.php" method="POST">
<input type ="checkbox" name="note" value = "Note1"></input>
<input type="submit" value="Click Me" style="width:300px;">
</form>
Upon submit, the code redirects to formsubmit.php. Part of the code there is the following:
$db = new mysqli("sql...byethost8.com", "b8_163//....(database info));
$id = $_SESSION['id'];
.......
if(isset($_POST['note'])){
if($id){
$db->query("UPDATE answers SET WordLevel = 'Difficult' WHERE user_id=$id"); //<<<UPDATES SUCCESSFULLY
$notevalue=$_POST['note'];
$db->query("INSERT INTO answers (user_id, ValueColumn) VALUES ($id,'$notevalue')"); //<<<<<DOESN'T UPDATE
The WordLevel column updates successfully, but the value of the input named note does not insert into the column titled ValueColumn. This was working in my code a few days ago but it somehow stopped working. I tried different iterations of single quotes around $id and $notevalue but nothing seems to resolve the issue.
Any help would be much appreciated!
Execute and clear before the second query.
O you can try concating queries together using semicolon
$db->query("FIRST QUERY ; SECOND QUERY");
If you dont need the output of first query.
PDO multiple query
mysqli multiple query
might also help real_query

Pass foreign key via $_GET

I have an online courses CRUD application. It has, among other pages, an instructor BIO page.
First, the instructors are added, in an users table, with basic data: first_name, last_name, and email; then a BIO can be added, optionally, for any instructor. There is a second database table, called "bios", to serve this purpose.
I need to pass $user_id into the courses table, (as foreign KEY) an for that purpose i use $_GET:
<?php
$user_id = $_GET['id'];
if(isset($_POST['submit-btn'])) {
$no_courses = $_POST['no_courses'];
$years_exp = $_POST['years_exp'];
$fav_lang = $_POST['fav_lang'];
$courses = $_POST['courses'];
$sql = "INSERT INTO courses (user_id, no_courses, years_exp, fav_lang, courses) VALUES ('$user_id', '$no_courses', '$years_exp', '$fav_lang', '$courses')";
if (mysqli_query($con, $sql)) {
echo("<p>Instructor bio was added.</p>");
} else {
echo "Error: " . mysqli_error($con);
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="add_bio">
...
</form>
Using $_GET seems convenient because in a table with a lot of rows, containing instructors, on the right most cell/column, I have a set of link buttons for CRUD operations, "Add bio" being one of those buttons.
<a title="Add bio" href="add_bio.php?id=<?php echo $arr['id']?>"><span class="glyphicon glyphicon-plus-sign"></span></a>`
But instead of passing the $user_id variable so that the bio can be added, the server throws these errors:
Notice: Undefined index: id in E:\xampp\htdocs\courses\add_bio.php on line 7
Error: Cannot add or update a child row: a foreign key constraint fails
How can I pass the user's id if I want to keep the CRUD links mentioned above?
Thank you!
You may have some issues with the content being submitted.
A great troubleshooting approach would be to:
print_r($_GET);
or
print_r($_POST);
Another option is to also:
echo print_r($_GET, true);
The Second argument (True) tells the print_r function to return as a string instead of output to the browser.
Review that output and verify you are actually getting an "ID" value in your GET and POST variables.
Also, some security concerns, any data you take in from GET or POST or REQUEST or COOKIE should be "cleaned" you can look at:
mysqli_real_escape_string
Additionally, Never use PHP_SELF. In almost all cases, it can be manipulated to execute a Cross Site Scripting Attack, and that is bad news. if you want to submit the form to the current script, you can leave the "action" attribute as an empty string.
action=""
Hope this helps!!!
The form was missing this line, right above the submit button:
<input type="hidden" name="id" value="<?php $user_id;?>">

Specifying ID in Mysqli query in php

I'm working on a CMS site, I've got blog posts that I store in a database. I can create, edit and delete them. There's an issue though when I want to edit them.
I can't specify the WHERE clause in the update query to match the id of the blog post I'm trying to edit!
Suppose I've got a blog post with an id of '5'.
If I write this code for it, it works exactly the way it should.
$sqledit = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
But I don't want to edit just blog post #5, I want to edit the blog post that I'm updating. It seems to me this should work,
WHERE id= $_POST[id]";
... but it doesn't.
That just throws me an undefined id error. But it shouldn't because I can delete blog posts the exact same way with this particular code:
$sqldel = "DELETE FROM `paginas` WHERE id= $_POST[id]";
This does allow me to.
The code below is on the blog page, the edit query is in its own edit.php page
if (isset($_POST['edit'])) // if pressed, execute
{
echo
'<br><br> <div class="blogscript">
<form action="edit.php" method="post">Edit your stuff<br>
<input type="text" placeholder='. $pagetitle . ' ><br><br>
<textarea id="message2" name="message"><p>' . $message . '</p></textarea><br>
<input type="submit" name="editsubmit" value="Confirm" />
<input type="hidden" name="id" value="' . $id . '">. </form></div>';
}
I look forward to any tips I should try out.
EDIT:
This is my edit.php page
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "cmsbase";
$MySQLi_CON = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);
if($MySQLi_CON->connect_errno)
{
die("ERROR : -> ".$MySQLi_CON->connect_error);
}
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $MySQLi_CON->error;
}
$MySQLi_CON->close(); //close connection
echo "<script>alert('Edited');location.href='index.php';</script>";
?>
EDIT: This is what the var_dump contains
In order for values to be present in $_POST, you need to have some element (e.g. <input>, <select>, <textarea>) inside your form with a name attribute set to the $_POST key you want.
You can add a hidden input to your form for id.
<input type='hidden' name='id' value='" . $id . "'>
Assuming you are getting the $message variable shown in that form code by selecting from your database, you should be able to get the id from there as well, or potentially from your $_GET if that is how you determine which post is being displayed.
(While this is not actually an answer, what I want to say does not fit in the comments)
Your line
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
Is horrific. This is the stuff of nightmares. Lets say that POSTed data in a form, is posted from a script from some robot somewhere, because I'm pretty sure you don't prevent XSRF in your code.
What if that script chose to post:
$_POST ==> array => message = "mwahahaha";
=> id = "1; DROP TABLE paginas;"
And you may think "how would they know my table name?" ,but that's easily found from other nefarious id inserts or other hacks on your code from other entry points which give a SELECT result, and many tables have common names such as "users" / "orders" / "baskets" / "touch-me" etc. (Ok well maybe not touch-me, but you get the idea).
Mysqli_real_escape_string() Could be used but thats only escaping quote marks and special characters, it does not mitigate SQL injection and compromise.
So, what should you do?
In this instance I want to draw your attention to PHP type juggling. Unlike many other languages, PHP has implied data types rather than specific data tyes, so a data type of "1.06" can be string and juggled to being a float as well.
Your id parameter in your MySQL is very probably a numeric integer value, so how can you be sure that the value of $_POST['id'] is also in integer rather than a SQL Instruction?
$id = (int)$_POST['id'];
This forces the value to be an integer, so
$id = (int)"1; DROP TABLE paginas;";
Is actually processed as $id = 1. Therefore saving you lots of compromised tables, spam rows and other nefarious rubbish all over your website, your database and your reputation.
Please take the following concept on board:
NEVER EVER TRUST ANY USER SUBMITTED CODE.
EVER

Select Data from Database with Id From URL

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.

Categories