I have one page which has one input text box and that data needs to be either inserted or updating the existing row.
I will echo it later, that is under control.
<form method="post" name="tapahtuma">
Submit:
<input type="text" name="auts[]">
<input type="button" value="Ilmoita">
</form >
<?php
if(isset( $_POST["tapahtuma"]) ) {
$link = mysql_connect("localhost","root","","db");
mysqli_query($link, "INSERT INTO table (column) VALUES ('".$auts."')");
$auts = mysql_real_escape_string($_POST['auts']);
mysqli_close($link);
}
?>
According to the code provided.
Changes
Change <input type="button" value="Ilmoita"> to <input type="submit" name="Ilmoita" value="Ilmoita">
Change if(isset( $_POST["tapahtuma"]) ) { to if(isset( $_POST["Ilmoita"]) ) {
Change $link = mysql_connect("localhost","root","","db"); to $link = mysqli_connect("localhost","root","","db");
Put $auts = mysql_real_escape_string($_POST['auts']); before mysqli_query
Updated Code
<form method="post" name="tapahtuma">
<input type="text" name="auts">
Submit: <input type="submit" name="Ilmoita" value="Ilmoita">
</form >
<?php
if(isset( $_POST["Ilmoita"]) ) {
$link = mysqli_connect("localhost","root","","db");
$auts = mysql_real_escape_string($_POST['auts']);
mysqli_query($link, "INSERT INTO table (column) VALUES ('".$auts."')");
mysqli_close($link);
}?>
I will suggest you to use prepared statements to avoid SQL Injections
<form method="post" name="tapahtuma">
<input type="text" name="auts">
Submit: <input type="submit" name="Ilmoita" value="Ilmoita">
</form>
<?php
if(isset($_POST["Ilmoita"])) {
$link = mysqli_connect("localhost","root","","db") or die("connection failed: " . mysqli_connect_error());
$result = mysqli_prepare($link, "INSERT INTO `table` (`column`) VALUES (?)");
mysqli_stmt_bind_param($result, "s", $_POST['auts']);
mysqli_stmt_execute($result);
mysqli_close($link);
}?>
Quick Links
mysqli_prepare
How can I prevent SQL injection in PHP?
<form method="post" name="tapahtuma">
Vapaa teksti: <input type="text" name="auts">
<input type="submit" value="ilmoita" name="ilmoita">
</form >
<?php
if(isset( $_POST["ilmoita"]) ) {
$link = mysqli_connect("localhost","root","","db");
$auts = mysqli_real_escape_string($link, $_POST['auts']);
mysqli_query($link, "INSERT INTO table (column) VALUES ('$auts')");
mysqli_close($link);
}?>
What I did, is that I used mysqli_real_escape_string instead of mysql_real_escape_string and also added the $link there as well.
I will test with the prepared statements sometime, but at least this works and it really isn't a concern with the sqli exploits.
Related
I'm a beginner at coding (I just have a small experience with Visual Basic and Pascal) and now I'm trying to learn some Web Development using O'Reilly's book "Learning PHP, MySQL, JavaScript, CSS & HTML 5".
The problem is that he is using MySQL instead of MySQLi, so I need to do small changes when I'm following thought the exercises.
In a chapter called "Accessing MySQL databases using PHP" he built a form where the user can add a new book (with title name, author, year, category and ISBN) to the database. My problem is that I have some error than doesn't allow to see in the web page the new book submitted.
I'm not sure, but I think it has to be something with the get_post and mysqli_real escape_string part.
This is the code I've written:
<?php //sqltest.php
require_once 'login.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysqli_error($db_server));
mysqli_select_db($db_server, $db_database)
or die ("Unable to select database: " . mysqli_error($db_server));
//Deleting a record.
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn = '$isbn'";
if (!mysqli_query($db_server,$query))
echo "DELETE failed: $query<br>" .
mysqli_error($query) . "<br><br>";
}
//Add new elements to the database.
if (isset($_POST['author']) && //Isset -> Determine if a variable is set and is not NULL.
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post($db_server, 'author');
$title = get_post($db_server, 'title');
$category = get_post($db_server, 'category');
$year = get_post($db_server, 'year');
$isbn = get_post($db_server, 'isbn');
}
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
//Displaying the form.
echo <<<_END
<form action = "sqltest.php" method="post"> <pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysqli_query($db_server, $query);
if (!$result) die ("Database acess failed: " . mysqli_query_error($result));
$rows = mysqli_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
}
function get_post($db_server, $var)
{
return mysqli_real_escape_string($db_server, $_POST[$var]);
}
mysqli_close($db_server);
?>
Just to explain my problem better: I fill the form with the details from the new book and then I submitted it but the new book doesn't appear on the web page (like the ones added before using MySQL command line).
Thanks for your time,
David
There is an error in your code, specific the name of database columns.
$query = "INSERT INTO classics (author, title, category, year, isbn) VALUES ('$author', '$title', '$category', '$year', '$isbn');";
My prepared statements for inserting data into a database are not working. I have had these issues accross the board but I am including one example just incase I am making a simple mistake. The query is running ok as I am getting a message which I placed myself within the code, however nothing is being entered into the actual database. MY issues so far with prepared statements is the lack of feedback you get when something isnt working. Any help would be greatly appreciated.
<?php
if(isset($_POST['newsubject'])){
include('../connection/conn.php');
//Prepare the insert statement
$insertquery = "INSERT INTO miiLearning_Tutors(tutor_id,subject_level,
price, subjects) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($conn, $insertquery)){
//bind variable to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iidi", $newtutor, $newsubject,
$newlevel, $newprice);
//Set Values
$newtutor = $_POST["tutorId"];
$newsubject = $_POST["subjects"];
$newlevel = $_POST["subjectlevel"];
$newprice = $_POST["price"];
mysqli_stmt_execute($stmt);
echo"<p>Query Ran</p>";
} else{
echo "ERROR: Could not prepare query: $query . " .mysqli_error($conn);
}
}
?>
HTML for form:
<form enctype="multipart/form-data" action='updatesubjects.php' method="post" id="update-subjects-form" name="new-subject" >
<fieldset>
<!--Tutor ID (Posted from previous page) -->
<input type="hidden" name="tutorId" value='<?php echo "$userarray[0]";?>'>
<!-- Subject -->
<div class="form-group">
<label for="subjects">Subject</label>
<select name="subjects" type="text" class="form-control">
<?php
if(mysqli_num_rows($subjectsresult)>0){
while($row = mysqli_fetch_assoc($subjectsresult)){
$get_subjectid = $row['subject_id'];
$get_subjectname = $row['subject'];
echo "<option value='$get_subjectid'>$get_subjectname</option>";
}
}
?>
</select>
</div>
<!-- Level -->
<div class="form-group">
<label for="subjectlevel">Subject Level</label>
<select name="subjectlevel" type="text" class="form-control">
<?php
if(mysqli_num_rows($levelresult) > 0){
while($row = mysqli_fetch_assoc($levelresult)){
$get_levelid = $row['level_id'];
$get_namelevel = $row['level'];
echo "<option value='$get_levelid'>$get_namelevel</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<label for="subjectlevel">Price</label>
<input type='number' step='0.01' min='0' name='price'>
</div>
<button class="btn btn-primary" type="submit" name="newsubject" id="bookingsform">Submit form</button>
</fieldset>
</form>
I apologies for any poor indentation
You need to declare your variables and assign value to them before binding. At the moment you should have undefined variables.
On development environment ensure error reporting is on.
<?php
error_reporting(-1);
ini_set('display_errors', 1);
if(isset($_POST['newsubject'])){
include('../connection/conn.php');
//Set Values
$newtutor = $_POST["tutorId"];
$newsubject = $_POST["subjects"];
$newlevel = $_POST["subjectlevel"];
$newprice = $_POST["price"];
//Prepare the insert statement
$insertquery = "INSERT INTO miiLearning_Tutors(tutor_id,subject_level, price, subjects) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($conn, $insertquery)){
//bind variable to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iidi", $newtutor, $newsubject, $newlevel, $newprice);
mysqli_stmt_execute($stmt);
echo"<p>Query Ran</p>";
} else{
echo "ERROR: Could not prepare query: $query . " .mysqli_error($conn);
}
}
?>
hi i am having a contact form in my website where user can optionaly fill some of the fields and after click on submit button data save in to the database all of this worked fine until i decide to sanitize my code from sql injection as i mentioned at first before trying to sanitize it from sql injection it worked properly as i showed in below code
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
//insert to database
$insert =mysqli_query($connect,"INSERT INTO $db_table VALUES (to simplify code i do not write this part)");
}
?>
now i have to fill all the dropdown lists and checkboxes otherwise it gives error "column '' can not be null". also i can not insert date and time into database it gives the same error. here is my code when i protect it fron sql injection:
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
if(isset($_POST['submit'])){
//insert to database
$query = mysqli_prepare($connect, "INSERT INTO $db_table VALUES (?,?,?,?)");
/* bind parameters for markers */
mysqli_stmt_bind_param( $query, "ssss", $_POST[name],$_POST['check1'],$_POST['case'],$_POST['date_clicked']);
// execute query
if ( mysqli_stmt_execute($query) ) {
echo "Successfully inserted " . mysqli_affected_rows($connect) . " row";
} else {
echo "Error occurred: " . mysqli_error($connect);
}
}
?>
please help me
Make sure that your variables exist. This is necessary because your checkbox, for example, will be null if not checked and that could be a problem for the table you are using. You could set defaults and then insert it.
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$check1 = !empty($_POST['check1']) ? $_POST['check1'] : '';
$case = !empty($_POST['case']) ? $_POST['case'] : '';
$date_clicked = date('Y-m-d H:i:s');
// prepare and bind
$stmt = $connect->prepare("INSERT INTO `$db_table` (`name`, `check1`, `case`, `date_clicked`) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $name, $check1, $case, $date_clicked);
$stmt->execute();
$stmt->close();
I want to insert multiple data to mysql.
My PHP code which is Array input field:
pag1.php
<form method="post" action="page2.php">
<input type="text" name="option_id[]" size="1">
<input type="text" name="store_id[]" size="1">
<button type="submit" name="action" value="add" >Add</button>
</form>
page2.php
<?php
if(isset($_POST['action'])){
for ($i=0; $i < count($_POST['option_id']); $i++ ) {
$option_id = $_POST['option_id'][$i];
$store_id = $_POST['store_id'][$i];
// check if option id is exists or not
$result = mysql_query ("SELECT * FROM temp_cart WHERE option_id='$option_id' AND store_id='$store_id' ") or die (mysql_error());
if (mysql_num_rows($result) == 0){
//insert query
}
else {
//update query
}
}
}
?>
For loop is not work.
Your help would be very much appreciated.
I have two table: word(id,word,meaning) and userword(id,wordid,userid)
in both of them id is auto increment.
In a form I get word and the meaning from user and then I want to insert this word into these to table. Insertion to words works well but for insertion to userword I have to get wordid from words and then insert into userword but it doesn't work
here is my form:
<form action="InsertWord.php" method="post">
<input name="word" id="word" type="text" maxlength="255" />
<label for="user">:word</label></br></br>
<input name="meaning" id="mean" type="text" maxlength="255" />
<label for="pass">:meaning</label></br></br>
<input type="submit" value="insert" /></br></br>
</form>
and InsertWord.php:
<?php
session_start();
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
if(isset($_POST["word"]) && isset($_POST["meaning"]))
{
$word = $_POST["word"];
$meaning = $_POST['meaning'];
$user= $_SESSION['userid'];
mysql_query("INSERT INTO words (word,meaning) values ('".$word."','".$meaning."')") or die(mysql_error());
$qwordid = mysql_query("SELECT id FROM words WHERE word='$word'") or die(mysql_error());
$fwordid = mysql_fetch_array($qwordid);
$wordid= $fwordid['id'];
mysql_query("INSERT INTO userword (user_id,word_id) values ('".$user."','".$wordid."')") or die(mysql_error());
//HEADER('LOCATION: InsertIntoUserword.php');
}
else
die('wrong!');
?>
because I insert into words and then database not refreshed it doesn't work for userword
what can I do?
You can use mysql_insert_id() but I recomend change to mysqli or PDO extension, because mysql extension will be deprecated and remove in a future, you can see this in http://www.php.net/manual/en/function.mysql-insert-id.php
The function mysql_insert_id() returns the id of the last inserted row:
$wordid = mysql_insert_id();