I am so new in making project, so please don't mind. i created a code using php, html, css to store some data into mysql database. Everything is fine but the email value is stored as %email in the database. Can anybody help me please.
html code for email field:
<div class="row">
<div class="label">Email Id</div>
<div class="inputaddr">
<input type="text" id="email" required="required" class="detail" name="email"/>
</div>
<div class="label">Category</div>
<div class="inputmobile">
<input type="text" id="category" required="required" class="shortdetail" name="category"/>
</div>
</div> <!-- end of 5th row -->
.php file:
<?php
$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db('ssitdashboard', $conn) or die(mysql_error());
if(isset($_REQUEST['submit'])){
$fullname = $_POST['fullname'];
$fname = $_POST['fname'];
$mname = $_POST['mname'];
$raddr = $_POST['raddr'];
$laddr = $_POST['laddr'];
$email = $_POST['email'];
$sex = $_POST['sex'];
$dob = $_POST['dob'];
$bloodgroup = $_POST['bloodgroup'];
$mobile = $_POST['mobile'];
$rmobile = $_POST['rmobile'];
$category = $_POST['category'];
$usn = $_POST['usn'];
$branch = $_POST['branch'];
$sem = $_POST['sem'];
$eca = $_POST['eca'];
$year = $_POST['years'];
$quota = $_POST['quota'];
$que = "INSERT INTO personal_details(name, fname, mname, raddr, laddr, email, sex, dob, blood_group, mobile, rmobile, category, usn, branch, sem, eca, year, quota) VALUES ('$fullname', '$fname', '$mname', '$raddr', '$laddr', '%email', '$sex', '$dob', '$bloodgroup', '$mobile', '$rmobile', '$category', '$usn', '$branch', '$sem', '$eca', '$year', '$quota')";
if(mysql_query($que)){
// echo "<script>alert('You have registered successfully')</script>";
// echo "<script>window.open('http://www.ssit.edu.in')</script>";
header("Location:thankyou.html");
exit;
}
}
?>
In database the email field is taken as varchar(30)
You have a typo in your query, %email where you intended $email.
That being said, you should rip out all of this code and replace it with something that doesn't have gigantic SQL injection bugs in it. Either you must use mysql_real_escape_string on each and every $_POST value being inserted, or you should be using PDO.
Mistakes like this are a lot harder to make if you have parameterized queries. An example in PDO is:
# Using named data placeholders here
$pdo->prepare(
"INSERT INTO personal_details(name, fname, mname, raddr, laddr,
email, sex, dob, blood_group, mobile, rmobile, category, usn,
branch, sem, eca, year, quota)
VALUES (:fullname, :fname, :mname, :raddr, :laddr,
:email, :sex, :dob, :bloodgroup, :mobile, :rmobile, :category, :usn,
:branch, :sem, :eca, :year, :quota)";
# When executing you specify the data to be used. The same prepared statement can be
# executed many times with different data.
$pdo->execute(array('fullname' => $_POST['fullname'], 'fname' => $_POST['fname'], ...));
Try changing %email to $email in your SQL statement.
But, in addition, look into PDO, as this implementation is vulnerable to SQL Injection.
To elaborate on the PDO implementation, you could do something like this for your situation:
$username = "root";
$password = "";
$host = "localhost";
$dbname = "ssitdashboard";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}catch(PDOException $ex){
die("Failed to connect: ".$ex->getMessage());
}
Now you have a PDO connection stored in $db which you can query through. You may want to account for magic quotes if you're not using PHP 5.4, so keep that in mind.
Otherwise, create your query statement like so..
$query = "INSERT INTO personal_details ( name, fname, mname, raddr, laddr, email, sex, dob, blood_group, mobile, rmobile, category, usn, branch, sem, eca, year, quota ) VALUES ( :name, :fname, :mname, :raddr, :laddr, :email, :sex, :dob, :blood_group, :mobile, :rmobile, :category, :usn, :branch, :sem, :eca, :year, :quota )"
Afterwards, you want to bind the values from the $_POST variables to the parameters that have : in front of them (like :name). You do that like so:
$query_params = array( ':name' => $_POST['fullname'], ':fname' => $_POST['fname'], ':mname' => $_POST['mname'], ':raddr' => $_POST['raddr'], ':laddr' => $_POST['laddr'], ':email' => $_POST['email'], ':sex' => $_POST['sex'], ':dob' => $_POST['dob'], ':blood_group' => $_POST['bloodgroup'], ':mobile' => $_POST['mobile'], ':rmobile' => $_POST['rmobile'], ':category' => $_POST['category'], ':usn' => $_POST['usn'], ':branch' => $_POST['branch'], ':sem' => $_POST['sem'], ':eca' => $_POST['eca'], ':year' => $_POST['years'], ':quota' => $_POST['quota']);
Finally, now that you have the statement and the parameters, use the previously created $db variable to prepare and execute the statement.
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
Since we're just INSERTing variables into the database, that should be all that's needed. If you were SELECTing data though, you could do something like this AFTER you've done the above...
$rows = $statement->fetchAll();
And now you could refer to column headers within each $row of the database table by utilizing a foreach statement.
$bloodArray = array();
foreach($rows as $row){
if(isset($row['blood_group'])){
$bloodArray[] = $row['blood_group'];
}
}
Hope that helps out, sorry for the delay!
mistake is that i used %email in the query...
Related
I'm having some trouble where I'm pulling values from both a session and a form - for a ticketing system - and when someone uses an apostrophe, it breaks the code.
See below where I receive the data:
$name = $_POST["name"];
$topic = $_POST["topic"];
$urgency = $_POST["urgency"];
$subject = $_POST["subject"];
$details = $_POST["details"];
$username = $_SESSION["username"];
$imgloc = $_SESSION["imgloc"];
$isit = $_SESSION["isit"];
I later insert it into my MSQL database here:
$sql = "INSERT INTO tickets (id, ticketname, urgency, topic, submitted, subject, details, isticketimage, imgloc) VALUES ('', '$name', '$urgency', '$topic', '$userno', '$subject', '$details', '$isit', '$imgloc')";
How would I amend this code to avoid apostrophe's breaking my mysql command?
You can use PDO from php, it will avoid sql injections.
You can do something like this
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$sql = "INSERT INTO tickets (ticketname, urgency, topic, submitted, subject, details, isticketimage, imgloc) VALUES (?,?,?,?,?,?,?,?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$name, $urgency, $topic, $userno, $subject, $details, $isit, $imgloc]);
More info : https://www.php.net/manual/en/pdo.prepared-statements.php
mysqli_real_escape_string($dbConnection, $variable)
should do the trick.
So bassically I can't seem to send the array with the input values to my database.
I tried sending it seperately, it works, but it only sends the array or the way around. There are no errors.
if (isset($_POST['submit'])) {
$services = implode ("|", $_POST['services']);
mysqli_query($mysqli, "INSERT INTO klientai (package, name, surname, email, phone, message, services) VALUES('$_POST[package]', '$_POST[name]', '$_POST[surname]', '$_POST[email]', '$_POST[phone]', '$_POST[message]', '$services'");
}
mysql_query function is deprecated and is not secured, You should use another option.
You can use PDO for example:
https://www.php.net/manual/en/book.pdo.php
open connection
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
insert method 1
$sql = "INSERT INTO users (name, surname, sex) VALUES (?,?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$name, $surname, $sex]);
insert method 2
$data = [
'name' => $name,
'surname' => $surname,
'sex' => $sex,
];
$sql = "INSERT INTO users (name, surname, sex) VALUES (:name, :surname, :sex)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
also check https://phpdelusions.net/pdo_examples/insert and
https://www.startutorial.com/articles/view/pdo-for-beginner-part-1
In this method, you don't need to escape your strings for SQL injection and it should also solve your problem.
I'm writing PHP code to send user input to the database. And http://fwtest.ga/register.php is my URL. every time I click the URL or check the JSON data in JSONLint website I get "mysqli_stmt_bind_param(): "Number of variables doesn't match a number of parameters in prepared statement" here is Mycode
<?php
$con = mysqli_connect("hostname", "username", "password", "dbname");
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$email = $_POST["email"];
$password = $_POST["password"];
$user_id = $_POST["user_id"];
$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
('$first_name', '$last_name', '$email', '$password')");
mysqli_stmt_bind_param($statement, 'ssss', $first_name, $last_name, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
You are injecting the params and you are preparing the query at the same time, use ? to tell mysql where to place the data,remove the variables from the sql string
$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
(?, ?, ?, ?)");
I declared the five variables after a $con, and use only four of them mysqli_prepare function. Now it's working.
I am trying to INSERT data into a table and I am using mysqli API executing query.
$insert = "INSERT INTO pdhp_patient
(username, password, email, first_name,
last_name, dob, gender, s_s_n, i_n)
VALUES ('$username', '$password', '$email', '$first_name',
'$last_name', '$dob', '$gender', '$s_s_n', '$i_n');";
This is the query I am trying to execute.
mysqli_query($connection, $insert);
The previous line of code is for executing the query. This time the query returns false. I am unable to understand what the mistake is I Have even tried without the single quotes in the query. This however does not work.
Editted:
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$dob = $_POST['dob'];
$dob = date("m-d-Y", strtotime($dob));
$gender = $_POST['gender'];
$cid = $_POST['country'];
$sid = $_POST['city'];
$s_s_n = $_POST['s_s_n'];
$i_n = $_POST['i_n'];
global $connection;
if(isset($_POST['type']) && $_POST['type']==="patient"){
$insert = "INSERT INTO pdhp_patient (username, password, email, first_name, last_name, dob, gender, s_s_n, i_n) VALUES ('$username', '$password', '$email', '$first_name', '$last_name', '$dob', '$gender', '$s_s_n', '$i_n');";
$insert = mysql_prep($insert);
$result = mysqli_query($connection, $insert);
if ( $result === false ) {
echo mysqli_error($connection);
exit;
}
if($val){
echo "This must be working";
}else{
echo "This was not working";
}
}elseif(isset($_POST['type']) && $_POST['type']==="doctor"){
$insert = "INSERT INTO pdhp_doctor (username, password, email, first_name, last_name, dob, gender, s_s_n, i_n) VALUES ($username, $password, $email, $first_name, $last_name, $dob, $gender, $s_s_n, $i_n);";
$insert = mysql_prep($insert);
mysqli_query($connection, $insert);
}elseif(isset($_POST['environment_radio']) && $_POST['type']==="environment"){
$insert = "INSERT INTO pdhp_environmentalist (username, password, email, first_name, last_name, dob, gender, s_s_n, i_n) VALUES ($username, $password, $email, $first_name, $last_name, $dob, $gender, $s_s_n, $i_n);";
$insert = mysql_prep($insert);
mysqli_query($connection, $insert);
}
Some more code for proper info. This code chunk is what I wanna achieve. this is the full code.
Thanks.
Give a man a fish, he eats today. Teach a man to fish, he eats everyday
Add some error checking
$insert = "INSERT INTO pdhp_patient
(username, password, email, first_name,
last_name, dob, gender, s_s_n, i_n)
VALUES ('$username', '$password', '$email', '$first_name',
'$last_name', '$dob', '$gender', '$s_s_n', '$i_n');";
$result = mysqli_query($connection, $insert);
if ( $result === false ) {
echo mysqli_error($connection);
exit;
}
Then you can probably fix your own errors
Per your update and comment your issue is that you are escaping the whole query, and not the values that you are passing in. That is not how escaping works, with escaping you escape the values going in incase they contain 's which would break the SQL encapsulation. So instead do..
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$first_name = mysqli_real_escape_string($connection, $_POST['first_name']);
$last_name = mysqli_real_escape_string($connection, $_POST['last_name']);
$dob = mysqli_real_escape_string($connection, $_POST['dob']);
$dob = mysqli_real_escape_string($connection, date("m-d-Y", strtotime($dob)));
$gender = mysqli_real_escape_string($connection, $_POST['gender']);
$cid = mysqli_real_escape_string($connection, $_POST['country']);
$sid = mysqli_real_escape_string($connection, $_POST['city']);
$s_s_n = mysqli_real_escape_string($connection, $_POST['s_s_n']);
$i_n = mysqli_real_escape_string($connection, $_POST['i_n']);
and get rid of mysql_prep. You should probably read up a bit more on SQL injections:
http://php.net/manual/en/security.database.sql-injection.php
https://www.owasp.org/index.php/SQL_Injection
The more secure approach is using parameterized queries with prepared statements.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I understand that there is a way to insert a constant from select statement which i found the source from here such as:
INSERT INTO MyTable(ColA,ColB,ColC)
SELECT 1,colBB,colCC FROM MyTable2
But is it possible to add an user input values (using php) instead of a constant value as well? If possible provide with example. Thanks in advance.
UPDATED:
I tried to create a simple web page however there are some syntax error that i have no idea to solve it:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\webservice\result.php on line 10
Below are my codes:
<?php
//start a session
require("config.inc.php");
$username = $_SESSION["username"];
if(!empty($_POST)){
//check if user choose non-required drop down list
if(empty($_POST['subcategory'])){
if(empty($_POST['yearofstudy'])) {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty";
$query_params = array(
':faculty' => $_POST['category'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
else {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND year_of_study = :yearofstudy";
$query_params = array(
':faculty' => $_POST['category'],
'yearofstudy' => $_POST['yearofstudy'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
}
else {
if(empty($_POST['yearofstudy'])) {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND course = :course";
$query_params = array(
':faculty' => $_POST['category'],
':course' => $_POST['subcategory'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
else {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND year_of_study = :yearofstudy AND course = :course";
$query_params = array(
':faculty' => $_POST['category'],
'yearofstudy' => $_POST['yearofstudy'],
':course' => $_POST['subcetagory'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
}
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
}
Here is an edited code snippet of mine that accomplishes what you are trying to. So in my form file I have something like this for contributing to a project:
<form name="contribute" method="post" action="contribute-dbquery.php" onsubmit="return validateForm()">
First Name:
<input name="nameValue" type="text" size="40" maxlength="12" required/>
<input name="Submit" type="submit" value="Add"/>
</form>
So what it says is when Add is goto Tcontribute-dbquery.php with the value of nameValue. Then in my contribute-dbquery.php I assign nameValue from the form to $name and then assign inset it into my database. I assigned it to a variable because I used it on that page as well. You can inset it right into the database if you want.
$name = $_POST['nameValue'];
$insert_sql = "INSERT INTO mastertable (name) VALUES (' " . $name . " ')";
If this helps mark it as answered. Let me know if you need any help.