This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I have been trying to input data from $_Post variables but I cannot spot where the error is? Hope you can help me.
Below is the code:
$conn = mysql_connect("localhost", "root");
if (isset($_POST['studLog'])) {
$uName = $_POST['uName'];
$pWord = $_POST['pWord'];
mysql_select_db("sis_main", $conn);
if (mysql_num_rows(mysql_query("SELECT * from student where stud_uname='$uName' and stud_pword='$pWord'"))) {
include("stud-view.html");
} else {
echo 'Account doesnt exist!';
echo "<br><br>";
echo "<a href='stud-start.html'>GO BACK!</a>";
}
} else if (isset($_POST['studReg'])) {
mysql_select_db("sis_main", $conn);
$stdID = $_POST['studID'];
$fname = $_POST['firstNme'];
$mname = $_POST['midNme'];
$lname = $_POST['lastNme'];
$stadd = $_POST['stAdd'];
$ctadd = $_POST['ctAdd'];
$bdate = $_POST['bDate'];
$gendr = $_POST['gender'];
$email = $_POST['email'];
$mobno = $_POST['mobNum'];
$uname = $_POST['newUName'];
$pword = $_POST['newPWord'];
$age = birthday($bdate);
if (mysql_query("INSERT INTO student values (`$stdID`,`$fname`,`$lname`, `$mname`,`$stadd`,`$ctadd`,`$age`,`$bdate`,`$gendr`, `$email`,`$mobno`,`$uname`,`$pword`);")) {
echo 'Account Successfully Regsitered!';
} else {
echo 'ERROR: '.mysql_error();
echo "<a href='stud-start.html'>GO BACK!</a>";
}
}
}
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '#gmail.com, 09981744039, kuyschan, kuyschan)' at line 1
This is suppposed to be a comment, but i have a low reputation here.
Before i answer your question, please do not use the mysql functions as its no longer supported . Consider a switch to either MYSQLI or PDO. Also, do not trust user input. Meaning do not directly post field values from your form to your database as an attcker can easily exploit it by adding funny javascripts or worse.
To your question,
In your insert statement, you did not specify the columns:
Try:
<?php
$sql = "INSERT INTO student (`studID`, `firstNme`, `lastNme`,`stAdd`,`ctAdd`,`bDate`,`gender`,`email`,`mobNum`,`newUName`,`newPWord`)VALUES
('" . mysqli_real_escape_string($con, $_POST['studID']) . "',
'" . mysqli_real_escape_string($con, $_POST['firstNme']) . "',
'" . mysqli_real_escape_string($con, $_POST['lastNme']) . "',
'" . mysqli_real_escape_string($con, $_POST['stAdd']) . "',
'" . mysqli_real_escape_string($con, $_POST['ctAdd']) . "',
'" . mysqli_real_escape_string($con, $_POST['bDate']) . "',
'" . mysqli_real_escape_string($con, $_POST['gender']) . "',
'" . mysqli_real_escape_string($con, $_POST['email']) . "',
'" . mysqli_real_escape_string($con, $_POST['mobNum']) . "',
'" . mysqli_real_escape_string($con, $_POST['newUName']) . "',
'" . mysqli_real_escape_string($con, $_POST['newPWord']) . "')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Where $con is your database connection.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
Related
I have re-written this question because of all the down votes and it would seem that either no one understood the question or was unwilling to help a newbie. So I'll as it this way: Can someone tell/show me why this code does not work? (500 error)
OR... at the very least point me in the right direction? I AM WILLING TO LEARN, I just don't know where to begin or who/where to learn from as I am not sure what to even ask other than how do you run multiple "else" statements... that however left me more confused than I already am though!
Any "HELP" would be greatly appreciated!
<?php
$servername = "localhost";
$username = "****";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$bname = $_POST['bname'];
$baddress = $_POST['baddress'];
$bcity = $_POST['bcity'];
$bstate = $_POST['bstate'];
$zipcode = $_POST['zipcode'];
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Login FROM `USERS` WHERE Business_Name = '" . $_POST["bname"] . "' AND Business_Address = '" . $_POST["baddress"] . "' AND Business_State = '" . $_POST["bstate"] . "' AND Business_Zip = '" . $_POST["zipcode"] . "' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while ($row = $result->fetch_assoc())
{
echo "https://www.***.com/realsite.php?Login=" . $row["Login"] . "";
}
}
else
{
$sql = "SELECT Login FROM `DATA` WHERE Business_Name = '" . $_POST["bname"] . "' AND Business_Address = '" . $_POST["baddress"] . "' AND Business_State = '" . $_POST["bstate"] . "' AND Business_Zip = '" . $_POST["zipcode"] . "' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while ($row = $result->fetch_assoc())
{
echo "https://www.***.com/demo.php?Login=" . $row["Login"] . "";
}
}
else
{
$sql = "INSERT INTO `DATA` (Business_Name, Business_Address, Business_City, Business_State, Business_Zip)
SELECT '$bname', '$baddress', '$bcity', '$bstate', '$zipcode' FROM (SELECT 1) t
WHERE NOT EXISTS (SELECT Login, Business_Name,Business_Address FROM `DATA` WHERE Business_Name='$bname' AND Business_Address='$baddress')";
if (mysqli_query($conn, $sql))
{
echo "<a href='https://www.servedwell.com/realsite.php?Login=" . $row["Login"] . "'>LINK</a>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
}
?>
Credit goes to #Ancaron for properly formatting code and correcting a syntax error. Final posted code works fine.
I have 2 tables(violator and officer) and both of them have column name reference, now what I want to do is whenever I add a new value to the violator table, the value of its reference should be equal to the value of reference on officer table. I am new to programming but how can I achieve that? I couldn't quite understand the notes I can find on the internet. This is how I add values to the violator table:
php
<?php
$user_name = "Demo";
$password = "Demopass";
$server = "localhost";
$db_name = "TMTRO";
$con = mysqli_connect($server, $user_name, $password, $db_name);
if ($con) {
$Name = $_POST['name'];
$LName = $_POST['lname'];
$LNumber = $_POST['lnumber'];
$Violation = $_POST['violation'];
$Aplace = $_POST['aplace'];
$Address = $_POST['address'];
$PNumber = $_POST['pnumber'];
$OName = $_POST['oname'];
$RNumber = $_POST['rnumber'];
$DTime = $_POST['dtime'];
$query = "insert into violators (name,lname,lnumber,violation,aplace,address,pnumber,oname,reference,datetime) values ('" . $Name . "','" . $LName . "','" . $LNumber . "','" . $Violation . "','" . $Aplace . "','" . $Address . "','" . $PNumber . "','" . $OName . "','" . $RNumber . "','" . $DTime . "');";
$result = mysqli_query($con, $query);
if ($result) {
$status = 'OK';
} else {
$status = 'FAILED';
}
} else {
$status = 'FAILED';
}
echo json_encode(array("response" => $status));
mysqli_close($con);
?>
i am finding little bit difficult to check duplicate data from database using MYsql,PHP and angular.js.I am explaining my code below.
addUser.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user_name=$request->user_name;
$user_email=$request->user_email;
$mob_no=$request->mob_no;
$login_name=$request->login_name;
$password=$request->password;
$user_status=$request->user_status;
$con = mysql_connect('localhost', 'root', 'Oditek123#');
mysql_select_db('go_fasto', $con);
$selquery = "SELECT * FROM db_user WHERE login_name='".$login_name."' and mob_no='".$mob_no."' and email='" . $user_email . "'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0)
{
$erresult=mysql_fetch_array($selres);
header("HTTP/1.0 401 Unauthorized");
$erresult['msg'] = 'This user login name or mobile no or email is already exist.';
}else{
$qry ='INSERT INTO db_user (user_name,email,mob_no,login_name,password,user_status) values ("' . $user_name . '","' . $user_email . '","' . $mob_no . '","' .$login_name . '","' . $password . '","' . $user_status . '")';
$qry_res = mysql_query($qry);
$user_type = 5;
$display_name = $user_name."_admin";
$qry ='INSERT INTO db_Admin_Master (user_type,user_name,display_name,password) values ("' . $user_type . '","' . $login_name . '","' . $display_name . '","' .$password . '")';
$qry_res = mysql_query($qry);
$query='SELECT * from db_user order by user_id desc';
$res=mysql_query($query);
$result=mysql_fetch_array($res);
if ($result) {
$result['msg'] = "New User has added successfully";
} else {
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = "Sorry, User could not added ";
}
echo json_encode($result);
}
?>
If you will check my code i am checking three column such as login_name,email and mob_no from database and checking it inside if statement.Here even if i am inserting the same data again it is not checking and else part is executing.Please help me to resolve this issue.
$selquery = "SELECT *
FROM db_user
WHERE login_name='".$login_name."'
OR mob_no='".$mob_no."'
OR email='" . $user_email . "'";
use OR instead of AND try
<?php
require('conn.php');
session_start();
ini_set('default_charset', 'UTF-8');
conopen();
mysql_query("SET NAMES utf8;");
$idedit = $_SESSION['id'] ;
$firstname = mysql_real_escape_string($_POST['firstnameedit']);
$lastname = mysql_real_escape_string($_POST['lastnameedit']);
$email = mysql_real_escape_string($_POST['emailedit']);
$username = mysql_real_escape_string($_POST['usernameedit']);
$password = mysql_real_escape_string($_POST['passwordedit']);
$query = " UPDATE `users` SET `firstname`= '" . $firstname . "',`lastname`='" . $lastname . "',`email`='" . $email . "',`username`='" . $username . "',`password`='" . $password . "', WHERE id = '" . $idedit . "'";
if (mysql_query($query) === true) {
echo '<meta http-equiv="Refresh" content="0; URL=profile.php" />';
}
else {
echo 'wrong';
}
conclose();
?>
I don't know why the echo output is incorrect. Can anyone tell me what's wrong? I'm trying to redirect to profile.php. What could be causing the query to return false?
You have an extra comma before the where clause.
Try this:
$query = " UPDATE `users` SET `firstname`= '" . $firstname . "',`lastname`='" . $lastname . "',`email`='" . $email . "',`username`='" . $username . "',`password`='" . $password . "' WHERE id = '" . $idedit . "'";
In general, you should learn to print out the query after variable substitution to see what the real query is. Errors are usually obvious when you do this.
I think the problem is the comma in front of the WHERE in your query.
Different from this question, but similar in that I don't get an error when adding information to my database.
$sql = "INSERT INTO 'nlcc_ver1'.'tUsers' ('userID', 'userName', 'userPassword', 'userHash',
'user_first_name', 'user_last_name', 'user_corps', 'is_admin', 'is_trg', 'is_sup', 'is_co')
VALUES (NULL, '" . $userName . "', '" . $hash . "', '" . $salt . "', '" . $f_name . "', '" .
$l_name . "', '" . $corps . "', '" . $admin . "', '" . $trg . "', '" . $sup . "', '" . $co . "')";
$hostname_Database = "localhost";
$database_Database = "nlcc_ver1";
$username_Database = "root";
$password_Database = "";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli_query($mysqli, $sql);
echo "Query run. Inserted UserID " . mysqli_insert_id($mysqli) . "<br />";
Line breaks inserted to avoid sideways scrolling... It says on the web page that mysqli_insert_id($mysqli) is 0, and nothing is added to the table on my database. I do not see an error connecting to the database appearing, and MySQL is running on my server, and phpinfo() shows both the MySQL and MySQLI extension loaded. This is just a development machine, so don't worry about the security (i.e. no password). I have tried googling the problem, but am not finding too much. I don't know about object oriented PHP programming with ->, I am used to using _. Is this method still supported?
You've mixed procedural and object-oriented MySQLi styles. This has led to you trying to use the functions like mysqli_query($mysqli) instead of the member functions like $mysqli->query(). Your $mysqli is an object, not a resource handle.
And, you're not performing any error checking on your query. If you were, you'd see that you have mistakenly used single quotes to delimit table and field names, not backticks.
$sql = "INSERT INTO `nlcc_ver1`.`tUsers`
(`userID`, `userName`, `userPassword`, `userHash`,
`user_first_name`, `user_last_name`, `user_corps`,
`is_admin`, `is_trg`, `is_sup`, `is_co`)
VALUES (NULL, '" . $userName . "', '" . $hash . "', '" . $salt . "', '" .
$f_name . "', '" . $l_name . "', '" . $corps . "', '" . $admin .
"', '" . $trg . "', '" . $sup . "', '" . $co . "')";
$hostname_Database = "localhost";
$database_Database = "nlcc_ver1";
$username_Database = "root";
$password_Database = "";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if (!$result) {
printf("%s\n", $mysqli->error);
exit();
}
echo "Query run. Inserted UserID " . $mysqli->insert_id . "<br />";
I strongly suggest using the manual as your reference. It's quite clear on how to use these functions when you're using either procedural or object-oriented style MySQLi.
$mysqli_query($mysqli, $sql);
should be
mysqli_query($mysqli, $sql);
OR
$mysqli->query($sql);
AND later on
$mysqli->insert_id();
Look at this:
'nlcc_ver1'.'tUsers'
You have to use backticks here as quote character:
`nlcc_ver1`.`tUsers`
But however(assuming that the $ in $mysqli_query is just a typo): You will not get errors for the query , unless you use mysqli_error() right after executing the query.
SET AutoCommit = 1 before inserting
$mysqli->query('SET AUTOCOMMIT = 1');