SQL syntax error or server error? - php

Hey guys I am new to the whole database scene and trying to perform a relatively simple task but apparently I am doing something wrong. Every time I try to execute this statement I get a 1064 error telling me either my syntax is wrong or the server version is too old. the SQL server version is 5.1.x and I am running PHP5.
Here is my code:
$query = "INSERT INTO `cut_log` (`driver`, `date1`, `time`, `cut`, `flood`, `notes`) VALUES ($driver, $date, $time, $cut, $flood, $notes)";
$result = $mysqli->query($query);
if($result) {
echo "success";
} else {
echo "" . $mysqli->errno . $mysqli->error;
}

You're missing quotes around your string values:
$query = "INSERT INTO `cut_log` (`driver`, `date1`, `time`, `cut`, `flood`, `notes`) VALUES ('$driver', '$date', '$time', '$cut', '$flood', '$notes')";

Like John said, the problem is that it's missing quotes.
What you should have done is prepare the query to avoid SQL injection attacks:
$query = "INSERT INTO `cut_log` (`driver`, `date1`, `time`, `cut`, `flood`, `notes`)
VALUES (?, ?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("ssssss", $driver, $date, $time, $cut, $flood, $notes);
if($stmt->execute()) {
echo "success";
} else {
echo "" . $mysqli->errno . $mysqli->error;
}
}

Related

Query executed, but data not saved into database PHP/SQL

I'm trying to execute a SQL query that saves POST data into the database. The data comes in correctly, and the arrays that are coming with the POST data are converted to strings.
When the query gets executed the message 'Succesfully saved into database' appears, however the data isn't visible in the database, so there must be a little mistake inside my code, however I can't seem to find it.
See my code below:
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
mysqli_stmt_execute($stmt);
echo '<p>Succesfully saved into database</p>';
exit();
}
}
This is how the database looks like
Thanks in advance!
You should not assume that the query ran successfully because an exception was not thrown. You need to consider what the function returns and how many rows are affected before knowing if it ran successfully or not. Update your code to this and figure out what is going on:
Also check to make sure you are not just updating the same row over and over.
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
if ( mysqli_stmt_execute($stmt) ) {
echo '<p>Succesfully saved into database</p>';
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt) );
}
}
mysqli_stmt_close($stmt);
}

am trying to insert more than one row into the mysql database

When i var_dump($q), I can see the records that is to be inserted into the mysql database, but when I try to do this $result = mysqli_query($con,$q);, the system is not returning an error message neither is the record inserted.
<?php
$con = #mysqli_connect("localhost", "root", "", "troubleshoot_db") or
die(mysqli_error("Couldn't Establish a Connection"));
if( isset($_POST['submit']) )
{
$Grade = $_POST['Grade'];
foreach( $Grade as $key => $v )
{
$fault_code = $key;
$q = sprintf( 'INSERT INTO `history_tb` VALUES ("%s", "%s", "%s", "%s", "%s")', $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']);
//var_dump($q);
$result = mysqli_query($con,$q);
}
}
?>
INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);
$query = "INSERT INTO table_name( name, address) VALUES ('jony', 'test1'),('bob', 'test2')";
mysql_query($query);
There are two things to tackle before anything else.
Using prepared statements
Since we are using prepared statements, make use of this functionality for inserting multiple values.
Change your code into the following (only amended inside the if statement):
<?php
$con = #mysqli_connect("localhost", "root", "", "troubleshoot_db") or
die(mysqli_error("Couldn't Establish a Connection"));
if( isset($_POST['submit']) )
{
$Grade = $_POST['Grade'];
$stmt = $mysqli->prepare("INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)"); //Prepare the sql command
foreach ($Grade as $key => $v )
{
// Assuming all are strings for now
$stmt->bind_param("sssss", $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']); // Bind the values in order to the ?'s
$stmt->execute(); // Execute the completed sql command
}
$stmt->close(); // Close the database connection
}
?>
What we are doing here is saying my SQL is
INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)`
now loop through your array and call this SQL with the parameters given at each section of the loop.
This solves the first two issues of not using prepared statements and looping when using prepared statements.
Try this and lets see if records get inserted
I'd also check that the foreach is correct, maybe it needs to be
foreach ($Grade as $v)
but without seeing the data I can't confirm.
You can also take this further to add error handling:
if ($stmt = $mysqli->prepare("INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)"))
{
foreach ($Grade as $key => $v )
{
// Assuming all are strings for now
// Bind the values in order to the ?'s or log error
if(!$stmt->bind_param("sssss", $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']))
{
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
// Execute the completed sql command or log error
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
$stmt->close(); // Close the database connection
}
else
{
die('prepare() failed: ' . htmlspecialchars($con->error));
}
Edit: added error handling

sql error when submitting with php

My php files that submits an entry to a database table isn't working and I can't figure out why. It takes in an Ajax submit and I know that the problem isn't with the data, or the Ajax request as it processes as a success. The only issue is that no data is ever submitted to my database. I had this working before I changed to code to concatenate the address string where it was one variable before. Any advice would be great!
Here is the php files
UPDATE:::THIS IS THE UPDATED PHP FILE
<?php
require("dbinfo.php");
// Create connection
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['user_name'];
$street = $_POST['user_street'];
$city = $_POST['user_city'];
$state = $_POST['user_state'];
$country = $_POST['user_country'];
$zip = $_POST['user_zip'];
$address = $street.', '.$city.', '.$state.', '.$country.', '.$zip;
$shortAdd = $city.', '.$state.', '.$country;
$type = $_POST['user_color'];
$desc = $_POST['user_message'];
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK") {
$lat = $xml->result->geometry->location->lat;
$lon = $xml->result->geometry->location->lng;
}
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES (?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssssss', $name, $shortAdd, $lat, $lon, $type, $desc);
$stmt->execute();
$conn->close();
?>
While docliving's answer is correct, please take the extra step and use prepared statements. Your code is vulnerable to SQL injection attacks without it. It just takes a very minor change to convert it to use prepared statements. Here is how to do it with mysqli:
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES (?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssssss', $name, $shortAdd, $lat, $lon, $type, $desc);
$stmt->execute();
When #MySelfBoy wrote:
After the assignment, you have to execute SQL statements
He means that you have to execute your query
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES ('$name', '$shortAdd', '$lat', '$lon', '$type', '$desc');";
with the following instruction:
$conn->query($sql);
NOTE: I Still canĀ“t make comments, so I'm posting it here.

bind_param() Issues

I am getting issues with the bind_param function. I will post all the information below.
Error:
Fatal error: Call to a member function bind_param() on a non-object in /home4/lunar/public_html/casino/blogpost.php on line 88
MySQL 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 ':user, :title, :message, :image, :category, NOW())' at line 1
Query:
$user = $_COOKIE['user'];
$title = $_POST['title'];
$message = $_POST['message'];
$image = $_POST['image'];
$category = $_POST['category'];
$stmt = $mysqli->prepare("INSERT INTO `lunar_casino`.`posts` (`id`, `by`, `title`, `message`, `image`, `category`, `date`) VALUES(NULL, :user, :title, :message, :image, :category, NOW())");
echo $mysqli->error;
$stmt->bind_param(":user", $user);
$stmt->bind_param(":title", $title);
$stmt->bind_param(":message", $message);
$stmt->bind_param(":image", $image);
$stmt->bind_param(":category", $category);
$stmt->execute();
if(!$stmt){
echo "<font color='red'><b>There has been an error with our database! Please contact the website administrator!</b></font><br /><br />";
echo $mysqli->error;
} else {
echo "<font color='green'><b>You have successfully added a blog post!</b></font><br /><br />";
}
Any ideas why its like this?
As Rocket Hazmat mentioned you can only use question marks as bind parameter place holder.
You should do something similar:
$stmt = $mysqli->prepare("INSERT INTO `lunar_casino`.`posts` (`id`, `by`, `title`, `message`, `image`, `category`, `date`) VALUES(NULL, ?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
More details: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
on the first argument the s = string and i = integer. You need to specify which type of value you want to add to the database. If you want to add 5 values that are strings to the database then write 'sssss' if you want to insert 5 integers then write 'iiiii' if you have some integers values and some string values then you can adjust accordingly.
//so if your values are all strings then this would be correct :
$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
//so if your values are all integers then this would be correct :
$stmt->bind_param("iiiii", $user, $title, $message, $image, $category);
//if the first 2 are integers and the other 3 strings then this would be correct :
$stmt->bind_param("iisss", $user, $title, $message, $image, $category);
and so on.

INSERT INTO sqlsrv_query statement not working

When working with the sqlsrv_query command I can request data from the MSSQL server.
This works
But!
When I want to add data it returns the error [error:array].
The code I use for this is:
$tsql= "INSERT INTO dbo.VERLOF_events (id,
username,
soort,
afdeling,
description,
evdate,
trdate)
VALUES
(?, ?, ?, ?, ?, ?, ?)";
$var = array('', $username, $soort, $afdeling, $description, $evdate, $trdate);
if (!sqlsrv_query($conn, $tsql, $var))
{
die('Error: ' . sqlsrv_errors());
}
echo "1 record added";
The array values are set in the POST statement.
$afdeling = $row['Afdeling'];
$submit = #$_POST['submit'];
$description = #$_POST["description"];
$evdate = #$_POST["evdate"];
$trdate = #$_POST["trdate"];
$username = #$_SESSION['username'];
$soort = #$_POST['Dagen'];
Why does it return the array error?
I looked it up but could not find the problem returning the error.
Any help is appreciated!
The problem is probably you're trying to add an empty value in the id field. If you set identity on it with auto-numbering, you don't need to include it in your query :
$tsql= "INSERT INTO dbo.VERLOF_events (
username,
soort,
afdeling,
description,
evdate,
trdate)
VALUES
(?, ?, ?, ?, ?, ?)";
$var = array($username, $soort, $afdeling, $description, $evdate, $trdate);
if (!sqlsrv_query($conn, $tsql, $var))
{
die('Error: ' . sqlsrv_errors());
}
echo "1 record added";

Categories