PHP mysql can't insert database and error - php

Need help here...
I receive an error code saying...
SQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''students' (Lastname, Firstname, Middleinitial, Course, Year, Section, Studentnu' at line 1
by the way, i put add function in php using these codes...
$Lastname = $_POST['Lastname'];
$Firstname = $_POST['Firstname'];
$Middleinitial = $_POST['Middleinitial'];
$Course = $_POST['Course'];
$Year = $_POST['Year'];
$Section = $_POST['Section'];
$Studentnumber = $_POST['Studentnumber'];
$Violation = $_POST['Violation'];
$Punishment = $_POST['Punishment'];
$Violationdate = $_POST['Violationdate'];
$Punishmentstartdate = $_POST['Punishmentstartdate'];
$CSlength = $_POST['CSlength'];
$Add = $_POST['add'];
$records = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('records', $records);
$sql = ("INSERT INTO 'students' (Lastname, Firstname, Middleinitial, Course, Year, Section, Studentnumber, Violation, Punishment, Violationdate, Punishmentstartdate, CSlength) VALUES('$Lastname', '$Firstname', '$Middleinitial', '$Course', '$Year', '$Section', '$Studentnumber', '$Violation', '$Punishment', '$Violationdate', '$Punishmentstartdate', '$CSlength')");
$result = mysql_query($sql, $records);
if (!$result)
die("SQL Error: ".mysql_error());
echo "Success";
thanks for the answer.... :))

Get rid of the quotes around students. Either use ticks or nothing at all:
$sql = ("INSERT INTO `students` (Lastname, Firstname, Middleinitial, Course, Year, Section, Studentnumber, Violation, Punishment, Violationdate, Punishmentstartdate, CSlength) VALUES('$Lastname', '$Firstname', '$Middleinitial', '$Course', '$Year', '$Section', '$Studentnumber', '$Violation', '$Punishment', '$Violationdate', '$Punishmentstartdate', '$CSlength')");
FYI, you are wide open to SQL injections.

You just have to modify you code like this!
$Lastname = $_POST['Lastname'];
$Firstname = $_POST['Firstname'];
$Middleinitial = $_POST['Middleinitial'];
$Course = $_POST['Course'];
$Year = $_POST['Year'];
$Section = $_POST['Section'];
$Studentnumber = $_POST['Studentnumber'];
$Violation = $_POST['Violation'];
$Punishment = $_POST['Punishment'];
$Violationdate = $_POST['Violationdate'];
$Punishmentstartdate = $_POST['Punishmentstartdate'];
$CSlength = $_POST['CSlength'];
$Add = $_POST['add'];
$records = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('records', $records);
$sql = "INSERT INTO students (Lastname, Firstname, Middleinitial, Course, Year, Section, Studentnumber, Violation, Punishment, Violationdate, Punishmentstartdate, CSlength) VALUES('$Lastname', '$Firstname', '$Middleinitial', '$Course', '$Year', '$Section', '$Studentnumber', '$Violation', '$Punishment', '$Violationdate', '$Punishmentstartdate', '$CSlength')";
$result = mysql_query($sql, $records);
if (!$result)
die("SQL Error: ".mysql_error());
echo "Success";

Try this
$Lastname = $_POST['Lastname'];
$Firstname = $_POST['Firstname'];
$Middleinitial = $_POST['Middleinitial'];
$Course = $_POST['Course'];
$Year = $_POST['Year'];
$Section = $_POST['Section'];
$Studentnumber = $_POST['Studentnumber'];
$Violation = $_POST['Violation'];
$Punishment = $_POST['Punishment'];
$Violationdate = $_POST['Violationdate'];
$Punishmentstartdate = $_POST['Punishmentstartdate'];
$CSlength = $_POST['CSlength'];
$Add = $_POST['add'];
$records = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('records', $records);
$sql = ("INSERT INTO students (Lastname, Firstname, Middleinitial, Course, Year, Section, Studentnumber, Violation, Punishment, Violationdate, Punishmentstartdate, CSlength) VALUES('$Lastname', '$Firstname', '$Middleinitial', '$Course', '$Year', '$Section', '$Studentnumber', '$Violation', '$Punishment', '$Violationdate', '$Punishmentstartdate', '$CSlength')");
$result = mysql_query($sql, $records);
if (!$result)
die("SQL Error: ".mysql_error());
echo "Success";

Remove the brackets around the INSERT statement as well as put the table and column names inside the backtick, change it as below
$sql = "INSERT INTO `students` (`Lastname`, `Firstname`, `Middleinitial`, `Course`, `Year`, `Section`, `Studentnumber`, `Violation`, `Punishment`, `Violationdate`, `Punishmentstartdate`, `CSlength`) VALUES('$Lastname', '$Firstname', '$Middleinitial', '$Course', '$Year', '$Section', '$Studentnumber', '$Violation', '$Punishment', '$Violationdate', '$Punishmentstartdate', '$CSlength')";
Since your code is too much vulnerable to SQL injection, it is better to use mysql prepared statements.Use MySQLi or PDO class to achieve it.

Related

error in SQL syntax when parsing xml files

I have tried to parsing data from url and this is part of xml data
-
<players category="Attackers">
<player id="206651">
<name>Thapelo Tale</name>
<firstname>Thapelo</firstname>
<lastname>Tale</lastname>
<team></team>
<teamid></teamid>
<nationality>Lesotho</nationality>
<birthdate>22/04/1988</birthdate>
<age>25</age>
<birthcountry>Lesotho</birthcountry>
<birthplace>Maseru</birthplace>
<position>Attacker</position>
<height>169 cm</height>
<weight></weight>
<image>
and using this code
<?php
$xmlLinq_player=simplexml_load_file("note.xml");
foreach($xmlLinq_player->player as $player) {
$player_id = $player->attributes()->id;
if($player_id){
$team_name=mysql_real_escape_string($player->team);
$team_id=mysql_real_escape_string($player->teamid);
if($team_id =='' || !$team_id){
$team_id=0;
}
$nationality=mysql_real_escape_string($player->nationality);
$fullname=mysql_real_escape_string($player->name);
$firstname=mysql_real_escape_string($player->firstname);
$lastname=mysql_real_escape_string($player->lastname);
$birthdate=$player->birthdate;
$birthdate=date('Y-m-d', strtotime(str_replace('-', '/', $birthdate)));
$birthcountry=mysql_real_escape_string($player->birthcountry);
$birthplace=mysql_real_escape_string($player->birthplace);
$logo=$player->image;
$position=mysql_real_escape_string($player->position);
$height=$player->height;
$weight=$player->weight;
$query = sprintf("INSERT INTO players (PlayerId,TeamId, FullName, FirstName, LastName, Nationality, BirthDate, BirthCountry, BirthPlace, PositionFull, Height,Weight,Photo)
VALUES($player_id, $team_id, '$fullname', '$firstname', '$lastname', '$nationality', '$birthdate', '$birthcountry','$birthplace','$position','$height','$weight','$logo')
ON DUPLICATE KEY UPDATE FullName = VALUES(FullName),FirstName = VALUES(FirstName), LastName = VALUES(LastName), Nationality = VALUES(Nationality), BirthDate = VALUES(BirthDate), BirthCountry = VALUES(BirthCountry),
BirthPlace = VALUES(BirthPlace),PositionFull = VALUES(PositionFull),Height = VALUES(Height),Weight = VALUES(Weight),Photo = VALUES(Photo)");
$result = mysql_query($query);
if (!$result){
$message = mysql_error() ;
//$message = 'Whole Query: ' .$query;
die($message);
}
}
}
}
}
?>
then it give this problem
( 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 '\n , 'Thapelo Tale', 'Thapelo', 'Tale', 'Lesotho', '1970-01-01', 'Lesotho','M' at line 2 ) please help .. how to solve this problem thanks
Check on duplicate key update syntax
INSERT INTO players (PlayerId,TeamId, FullName, FirstName, LastName, Nationality, BirthDate, BirthCountry, BirthPlace, PositionFull, Height,Weight,Photo)
VALUES($player_id, $team_id, '$fullname', '$firstname', '$lastname', '$nationality', '$birthdate', '$birthcountry','$birthplace','$position','$height','$weight','$logo')
ON DUPLICATE KEY UPDATE FullName = '$FullName',FirstName ='$FirstName', LastName = '$LastName',
Nationality = '$Nationality', BirthDate = '$BirthDate', BirthCountry = '$BirthCountry',BirthPlace = '$BirthPlace',PositionFull = '$PositionFull',
Height = '$Height',Weight = '$Weight',Photo = '$Photo'");

I've created a submission form but when I hit submit I get the following response

ERROR: Could not able to execute
INSERT INTO applications (title, surname, maiden_name, first_name, marital_status, gender, country, date_of_birth, address, email, home_numbers, work_numbers, cell_phone, application_results, next_of_kin_name, next_of_kin_relationship, next_of_kin_number, chronic_disease)
VALUES ('Mr', 'McLaren', '', 'Richard', 'Single', 'Male', 'England', '', 'Room 67 14 Tottenham Court Road London England W1T 1JY', 'mclaren.richard#gmail.com', '020 7946 0072', '020 7946 0549', '020 7946 0760', 'Elizabeth', 'Mother', '020 7946 0831', 'No') ).
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 ')' at line 6
The php code is:
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "cas");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$title = mysqli_real_escape_string($link, $_REQUEST['title']);
$surname = mysqli_real_escape_string($link, $_REQUEST['surname']);
$maiden_name = mysqli_real_escape_string($link, $_REQUEST['maiden_name']);
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
$marital_status = mysqli_real_escape_string($link, $_REQUEST['marital_status']);
$gender = mysqli_real_escape_string($link, $_REQUEST['gender']);
$country = mysqli_real_escape_string($link, $_REQUEST['country']);
$date_of_birth = mysqli_real_escape_string($link, $_REQUEST['date_of_birth']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$home_number = mysqli_real_escape_string($link, $_REQUEST['home_number']);
$work_number = mysqli_real_escape_string($link, $_REQUEST['work_number']);
$cell_phone = mysqli_real_escape_string($link, $_REQUEST['cell_phone']);
$next_of_kin_name = mysqli_real_escape_string($link, $_REQUEST['next_of_kin_name']);
$next_of_kin_relationship = mysqli_real_escape_string($link, $_REQUEST['next_of_kin_relationship']);
$next_of_kin_number = mysqli_real_escape_string($link, $_REQUEST['next_of_kin_number']);
$chronic_disease = mysqli_real_escape_string($link, $_REQUEST['chronic_disease']);
// attempt insert query execution
$sql = "INSERT INTO applications (title, surname, maiden_name, first_name, marital_status,
gender, country, date_of_birth, address, email, home_numbers, work_numbers, cell_phone,
application_results, next_of_kin_name, next_of_kin_relationship, next_of_kin_number, chronic_disease)
VALUES ('$title', '$surname', '$maiden_name', '$first_name', '$marital_status',
'$gender', '$country', '$date_of_birth', '$address', '$email', '$home_number', '$work_number', '$cell_phone',
'$next_of_kin_name', '$next_of_kin_relationship', '$next_of_kin_number', '$chronic_disease') )";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Your INSERT statement had an extra bracket at the end of sentence.
INSERT INTO .... '$chronic_disease') >)< ';
INSERT syntax
INSERT INTO table(columns) VALUES(values)
$sql = "INSERT INTO applications (title, surname, maiden_name, first_name, marital_status,
gender, country, date_of_birth, address, email, home_numbers, work_numbers, cell_phone,
application_results, next_of_kin_name, next_of_kin_relationship, next_of_kin_number, chronic_disease)
VALUES ('$title', '$surname', '$maiden_name', '$first_name', '$marital_status',
'$gender', '$country', '$date_of_birth', '$address', '$email', '$home_number', '$work_number', '$cell_phone',
'$next_of_kin_name', '$next_of_kin_relationship', '$next_of_kin_number', '$chronic_disease')";
You had a extra ) at the end of the above statement.

The INSERT query returns false in php with mysql. Using msqli_query($dbcon, query)

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

php codes stops running halfway through

I have created a php function that allows users to save their address on the database. My issue is that part of the code doesn't run at all. The code stops running at $result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";
It then starts working when it reaches this line of code $insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress)
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";
I haven't received any syntax errors when running the code either.
Any help would be grateful.
<?php
include 'dbconnect.php';
$connection = mysqli_connect($db_host, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno($connection)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Getting data from HTML Form
$Number = $_POST['streetnumber'];
$Street = $_POST['street'];
$Town = $_POST['town'];
$Postcode = $_POST['postcode'];
$Username = $_POST['Username'];
$sql = mysqli_query($connection, "SELECT * FROM Userv2 WHERE Username = '".$Username."'");
if ($sql){
while($row = mysqli_fetch_array($sql)){
$id = $row['Id'];
}
}
$result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";
$sql1 = mysqli_query($connection, $result2);
$count = count($sql1);
if($count >=1){
echo 'Sorry you can only have 1 default address';
}
$insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress)
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";
$result = mysqli_query($connection, $insert_query);
header("Location: http://sots.brookes.ac.uk/~10031187/viewaddress.php");
mysqli_close($connection);
?>
maybe it's better to use
SELECT COUNT(Userid) AS countId FROM..
if ($row['countId'] > 1) {
that way the query will always return something, now there is a chance your query can return false..
what is the output of var_dump($sql1); ?
$sql1 is a resulset. You cannot count the number of lines like this.
Try :
$sql1_count = mysqli_num_rows($sql1)

Update values which match the same ip php/sql

<?
$nick = $_POST['nick'];
$link = $_POST['link'];
$regiment = $_POST['regiment'];
$message = $_POST['message'];
$date = date('Y-m-d H:i:s');
$ip = $_SERVER['REMOTE_ADDR'];
$servername="localhost";
$username="pp";
$conn= mysql_connect($servername,$username, mygas13)or die(mysql_error());
mysql_select_db("pp",$conn);
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$sql = "SELECT TIMEDIFF(NOW(), `LastPost`) AS 'TimeSinceLast'
FROM `userTable`
WHERE `ip` = '{$ip}'
AND `LastPost` > DATE_SUB(NOW(), INTERVAL 1 DAY)";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$timeSinceLast = date("G\h i\m s\s", strtotime($row['TimeSinceLast']));
$sql="insert into userTable (nick,link,message,regiment,ip,date,submitted) VALUES ('$nick', '$link', '$message', '$regiment', '$ip', '$date', 'Yes') ";
$result=mysql_query($sql,$conn) or die(mysql_error());
}
else {
$servername="localhost";
$username="pp";
$conn= mysql_connect($servername,$username, mygas13)or die(mysql_error());
mysql_select_db("pp",$conn);
$sql="insert into userTable (nick,link,message,regiment,ip,date,submitted) VALUES ('$nick', '$link', '$message', '$regiment', '$ip', '$date', 'No')";
$result=mysql_query($sql,$conn) or die(mysql_error());
mysql_close($connection);
}
header("Location: thanks.html");
?>
This is my input.php. It submits the data but it also checks if multiple submissions come from one ip in 1day period. What i can't do is to update the value submitted for the rest of his/her submissions with yes. I have tried DUPLICATE KEY UPDATE but it did not work

Categories