data not inserting I am using php mysql [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
<?php
error_reporting(0);
//connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "visionci";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//file properties
//if (isset($_POST['image']))
$file = $_FILES["image"]["tmp_name"];
if (!isset($file))
{//echo "Please Select an Image";
}
else
{ $name = $_POST["name"];
$rollno = $_POST["rollno"];
$address = $_POST["address"];
$duration = $_POST["duration"];
$course=$_POST["course"];
$fname = $_POST["fname"];
$mname = $_POST["mname"];
$image=addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$image_name= addslashes($_FILES["image"]["name"]);
$image_size= getimagesize($_FILES["image"]["tmp_name"]);
if($image_size==FALSE)
{echo "That's not an Image";}
else
{
$sql = "INSERT INTO insert (rollno,name,image,address,duration,fname,mname,course)VALUES('$rollno','$name','$image','$address','$duration','$fname','$mname','$course')";
if ($conn->query($sql) === TRUE)
{
//$lastid= mysqli_insert_id($conn);
echo "Record Inserted Successfully!";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
Above is my code. I am getting some garbage value followed by an 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 'insert (rollno,name,image,address,duration,fname,mname,course)VALUES('','','ÿØ' at line 1]
Let me know where I am getting problem I am Stuck.

Change your table name from insert. That can't be distinguished from the command insert, and you couldn't select from a table named insert without escaping
INSERT INTO something_else
or
INSERT INTO `insert`

$sql = "INSERT INTO insert (rollno,name,image,address,duration,fname,mname,course)VALUES('$rollno','$name','$image','$address','$duration','$fname','$mname','$course')";
Here you have used a "insert" as a table name. It is a Reserved key word in MySQL so change that name in to another value and try again.

Related

error in passing multiple parameters in MySQL stored procedure from php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
i have an stored procedure InsertStudent in MySQL DB which is working fine from database,
now i am calling the above Sp from php by giving all the parameter its giving following error
Error: CALL InsertStudent(Mohd Maaz,455,1,2,0)
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 'Maaz,455,1,2,0)' at line 1
here is my code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "funed";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$StudentName = "Mohd Maaz";
$StudentClass = 1;
$StudentRollNo = 455;
$StudentSection = 2;
$StudentIsdltd = 0;
$sql = "CALL InsertStudent(".$StudentName.",".$StudentRollNo.",".$StudentClass.",".$StudentSection.",".$StudentIsdltd.")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
You just forgot to quote the parameters
replace
$sql = "CALL InsertStudent(".$StudentName.",".$StudentRollNo.",".$StudentClass.",".$StudentSection.",".$StudentIsdltd.")";
with
$sql = "CALL InsertStudent('".$StudentName."','".$StudentRollNo."','".$StudentClass."','".$StudentSection."','".$StudentIsdltd."')";
or I prefer to use the variables in the string directly without concatenating
$sql = "CALL InsertStudent('$StudentName','$StudentRollNo','$StudentClass','$StudentSection','$StudentIsdltd')";

INSERT TABLE using php variable

What is the correct syntax for the SQL INSERT INTO when using a php variable for table name. I have tried everything and it won't insert when I use php variable.
This is what I have so far. is this right?
$sql = "INSERT INTO ".$table." (`Name`) VALUES ('A')";
mysqli_query($conn, $sql);
if I switch $table to the actual table name, it works
$sql = "INSERT INTO 'myTable' ('Name') Values ('A')";
It works for me fine
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stack_over_flow";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
When Table Name is Variable
$DB_TBLName = "abc";
$sql_ac_valuee = "INSERT INTO $DB_TBLName (a, b ,c) VALUES "."('10','20','30')";
if ($con->query($sql_ac_valuee) === TRUE) {
}
else{
echo "Error: " . $sql_ac_valuee . "<br>" . $con->error;
}
When Use direct Table Name
$sql_ac_valuee = "INSERT INTO abc (a, b ,c) VALUES "."('10','20','30')";
if ($con->query($sql_ac_valuee) === TRUE) {
}
else{
echo "Error: " . $sql_ac_valuee . "<br>" . $con->error;
}
$query = "INSERT INTO $tname (place,dis,p_1,p_2,p_3,p_4,p_5,p_6) VALUES('$name','$discription','$bfile','$file1','$file2','$file3','$file4','$file5')";
$result =mysqli_query($link,$query);
if(!$result){echo mysqli_error($link);?>
This was my code and the output is:
Skardu.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 '(place,dis,p_1,p_2,p_3,p_4,p_5,p_6) VALUES('Sundus','Few people can afford the T' at line 1
its work fine when i use skardu instead of varible

Cant insert specific row into the database PHP MySQL JSON

I pulled the json into the php object and started putting data from that object into the database. I have 20 users in json and everyone succeded to go into the database except one which surname is O'Carolan. I think that error is in that single quote, smth about that. I read everything about sql injection and tried everything i found here on stackoverflow with the similar errors and still doesnt work. I tried with the PDO also and prepared statements and still doesnt work. Here I always get an 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 ' 'male')' at line 2. Also, when printing out the users from json it prints them properly and everything is ok there, just that 3rd user O'carolan wont go into to database.
My json is at http://dev.30hills.com/data.json and my code is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "30hills";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json_string = 'http://dev.30hills.com/data.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, false);
$elementCount = count($obj);
for ($x = 0; $x < $elementCount; $x++) {
$id = $obj[$x]->id;
$firstname = $obj[$x]->firstName;
$surname = $obj[$x]->surname;
//if (preg_match('/'.$special_chars.'/', $surname)){
// $surname = str_replace("'","",$surname);
//}
$age = $obj[$x]->age;
$gender = $obj[$x]->gender;
echo $id;
echo " ";
echo $firstname;
echo " ";
echo $surname;
echo "<br>";
mysqli_query($conn, "INSERT INTO user (`id`, `firstName`, `surname`, `age`, `gender`)
VALUES($id, '$firstname', '" . $surname . "', $age, '$gender')")
or die(mysqli_error($conn));
?>
The answer is that age = null in json wont insert into database, must make that nullable into the table

HTTP Post to MySQL inserting Blank Rows

I'm trying to setup a post string to enter data directly into the database from a remote system.
Post string example: http://www.domainname.com/insert.php?Phone=07000888888
This returns my expected success message however when I check the database the phone field is blank.
My PHP insert script looks like:
<?php
$servername = "localhost";
$username = "XXXX";
$password = "XXXX";
$dbname = "Client1";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$_POST[Phone]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Can anyone figure out why it's inserting a blank row with this?
There are a few problems with the code that as a server admin make me slightly uncomfortable. Hopefully we can fix that and your problem at the same time.
This is what I picked up on.
(I have removed empty lines for brevity)
<?php
// ...
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$_POST[Phone]')";
// ...
The first thing is you are correctly escaping the string and then not using the escaped string
<?php
// ...
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
However you never inspect the value to see if you have anything.
<?php
// ...
if(isset($_POST['phone'])){
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
}else{
echo '<p><b>Error:</b> "Phone" not given.</p>';
exit(0); // stop and do no more
}
// ...
Finally (just in case): If you are sending the data this way http://example.com/example.php?phone=123456789 that is $_GET.
<?php
// ...
if(isset($_GET['phone'])){
$phone = mysql_real_escape_string($_GET['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
}
// ...
One way or another you should now have safe, clean and functional code that does not add empty rows and cannot so readily be abused.
You code should be like this
<?php
$servername = "localhost";
$username = "XXXX";
$password = "XXXX";
$dbname = "Client1";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$phone = mysqli_real_escape_string($conn, $_GET['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('".$phone."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Without seeing your form, which would help I am assuming you are using GET not POST.
So you need to get your values with GET not POST if the following is the result of the form submission:
http://www.domainname.com/insert.php?Phone=07000888888
change:
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$_POST[Phone]')";
to
$phone = mysql_real_escape_string($_GET['Phone']);
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$phone')";
Additionally for some extra input validation you could do something like:
$phone = mysql_real_escape_string($_GET['Phone']);
if(!ctype_digit($phone)){
echo "Incorrect Phone Number format";
}
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$phone')";
That would make sure the phone number only has numbers in it (if that is indeed what you want and don't have +445498390 type numbers)
I finally figured it out.
The code itself was fine, it was the post string URL had an uppercase P in Phone.
once I changed it to phone it's now started working properly.
Thanks for all the help.
I was having this issue and it no matter what filtering I tried in PHP I could not stop the blank line from being inserted into my database records. What finally fixed the issue for me was adding .trim(); to my javascript variable. Hopefully, this will help someone else having similar issue!

PHP MySQL if row exists not doing anything

I am trying to get this piece of code to check if the line already exists in the database.
These lines get inserted into the database:
512150 # Merlinz is banned permanently by SO_Conner. # banned untill never for RDM
Now this piece of code checks if it already exists in the DB, if it doesn't exist we insert it.
$search = "permanently";
$logfile = "ban_list.txt";
$timestamp = time();
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search))
{
$check = mysql_query("SELECT * FROM `pincodes` WHERE `Pincode` = '$pincode' ");
if(mysql_num_rows($check) == 1) {
die(); }
else
{
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(stristr($line,$search))
$sql = "INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
// case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
}
Like I said, it is still inserting it into my Database even though the line is present in the database.
Thanks }
if(mysql_num_rows($check)>0) {
echo " ";
}
else
{
change your line of code to this,
this would check if it already exist.
Flies Away
Try checking in the following manner
if(mysql_num_rows($check) !== FALSE)
Also try printing the query to see how the value is embedding for debugging purpose...
If it's a ban list based on a unique username why not alter the table to make the column unique. This code will also delete duplicates in the column 'Ban'.
ALTER IGNORE TABLE ingamebanlist ADD UNIQUE (Ban);
Next, mysql_num_rows() is deprecated in php 5.5
http://php.net/manual/en/function.mysql-affected-rows.php
Your best bet (even if your mysql functions work) is to change the mysql function calls to mysqli function calls. They are more secure and up to date.As well as making sure there is a constant in your code so your not switching between them.
If you change the mysql commands to mysqli this should work.
mysqli_affected_rows($conn);
Lastly, if you change the 'Ban' column to unique and make use of the mysqli_affected_rows this code should be all you need to insert when doesn't exist.
mysqli_query($conn,"INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')");
$num = mysqli_affected_rows($conn);
if($num > 0)
{
echo "Successfully Inserted";
}
else if($num == 0)
{
echo "Line already exists";
}
else
{
echo "Insert Error";
}

Categories