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.
Related
I am trying to protect my queries from SQL injections, recently. I have started turning the strings I used to make the queries into statements, however, some of the strings I made need to make multiple queries simultaneously, because one insert's id will be added to the next one as a foreign key, which I'll get by using the LAST_INSERT_ID(), and I need them to be executed one after another because of it.
Can a statement hold multiple queries simultaneously and be executed at once?
Here's what the code was before, by the by.
$sql = "INSERT INTO `user_info`(`first_name`, `last_name`, `phone`, `cpf`)
VALUES ('{$firstName}', '{$lastName}', '{$phone}', '{$cpf}');";
$sql .= "SELECT LAST_INSERT_ID() INTO #mysql_variable_here;";
$sql .= "INSERT INTO `{$table}`(`email`, `password`, `active`,`user_info_id`, `created`, `role_id`" . $restaurantInsert . ")
VALUES ('{$email}','{$password}', 1, #mysql_variable_here, '{$created}', {$role}" . $restaurantValue . " );";
$sql .= "INSERT INTO `address`(number, street, city, state, zip, district, country, created, user_info_id)
VALUES ('{$number}', '{$street}', '{$city}', '{$stateCode}', '{$zip}', '{$district}', 'BR', '{$created}', #mysql_variable_here);";
$result = $conn->multi_query($sql);```
You can't execute multiple statements in a prepared query:
SQL syntax for prepared statements does not support multi-statements
(that is, multiple statements within a single string separated by ;
characters)
so you will need to prepare and execute each of the queries separately, using mysqli_stmt::insert_id to get the appropriate id value for the second and third queries:
$sql = "INSERT INTO `user_info`(`first_name`, `last_name`, `phone`, `cpf`)
VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $firstName, $lastName, $phone, $cpf);
$stmt->execute();
$insert_id = $stmt->insert_id;
$stmt->close();
$sql = "INSERT INTO `{$table}`(`email`, `password`, `active`,`user_info_id`, `created`, `role_id`" . $restaurantInsert . ")
VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssiisss', $email, $password, 1, $insert_id, $created, $role, $restaurantValue);
$stmt->execute();
$stmt->close();
$sql = "INSERT INTO `address`(number, street, city, state, zip, district, country, created, user_info_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$country = 'BR';
$stmt->bind_param('sssssssi', $number, $street, $city, $stateCode, $zip, $district, $country, $created, $insert_id);
$stmt->execute();
$stmt->close();
Note I'm not 100% certain what you're trying to achieve with role_id" . $restaurantInsert . ", you might need to edit the second query appropriately to use that.
I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
Unprepared version:
$sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
$date', 'Nominator/$location$newstring')";
mysqli_query($mysqli, $sql);
Replace $stmt-execute(); with $stmt->execute();
Also, don't use date and path in query. Rename them with some other name like date1 and path1.
Update your Query like below that will surely work (Tested Offline):
<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');
if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>
You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.
//Prepare your query first
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
I'm making a simple sign up/in form for a school assignment.
for some reason I can't get it to create a new column in my current table.
All of the information for the $_Get is coming up properly. I imagine its a syntax error i'm not seeing. Any help would be great. Thank you.
if ( $_GET['action'] == "create" )
{
print('test');
// -----------------------
// PERFORM DATABASE UPDATE
$fn = $_GET['fn'];
$ln = $_GET['ln'];
$id = $_GET['id'];
$user = $_GET['user'];
$tel = $_GET['tel_num'];
$email = $_GET['email'];
$bday = $_GET['birthday'];
$password = $_GET['password'];
$address = $_GET['address'];
print('test1');
mysql_select_db("advweb2");
$sql="INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES ('$user', '$password', '$email', '$fn', '$ln', '$address', '$tel', '$bday')";
print_r($sql);
print("<div style='color:green'>update successful</div>");
// -----------------------
$action = "signin";
}
You need to execute the query.
You should be using MySQLi or PDO as detailed here as mysql_query is deprecated.
Example with mysqli:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$stmt = $mysqli->prepare(
"INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param('ssssssss', $user, $password, $email, $fn, $ln, $address, $tel, $bday);
$stmt->execute();
/* ... */
$stmt->close()
?>
You need to make sure you clean your $_GET variables before inserting into the database to prevent SQL injection. A good read: how to prevent SQL injection.
Please don't use mysql_query, switch to mysqli or PDO instead.
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
$name = 'one';
$value = 1;
$stmt->execute();
$dbh = null;
Use Mysqli or PDO as explained by others but if you insist execute your query like this:
$sql=mysql_query("INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES ('$user', '$password', '$email', '$fn', '$ln', '$address', '$tel', '$bday')");
Because You prepared query and assigned it to the variable but for missed to execute it.
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.
I'm trying to implement my first prepared statement using mysqli.
At the moment I have this:
<?php
$con = new mysqli('example.com', 'user', 'password', 'database');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
$first = $_GET['firstname'];
$last = $_GET['surname'];
$dob = $_GET['dob'];
$address = $_GET['homeaddress'];
$college = $_GET['college'];
$emergname = $_GET['emergencyname'];
$emergnumber = $_GET['emergencynumber'];
$condition = $_GET['condition'];
$conditiondetails = $_GET['conditiondetails'];
$medication = $_GET['medication'];
$medicationdetails = $_GET['medicationdetails'];
if($stmt = $con->prepare("INSERT INTO medical ('forename', 'surname', 'dob', 'address', 'college', 'emergency_name', 'emergency_number', 'condition', 'condition_details', 'medication', 'medication_details') VALUES (:forename, :surname, :dob, :address, :college, :emergencyname, :emergencynumber, :condition, :conditiondetails, :medication, :medicationdetails)")){
$stmt->bind_param(':forename', $first);
$stmt->bind_param(':surname', $last);
$stmt->bind_param(':dob', $dob);
$stmt->bind_param(':address', $address);
$stmt->bind_param(':college', $college);
$stmt->bind_param(':emergencyname', $emergname);
$stmt->bind_param(':emergencynumber', $emergnumber);
$stmt->bind_param(':condition', $condition);
$stmt->bind_param(':conditiondetails', $conditiondetails);
$stmt->bind_param(':medication', $medication);
$stmt->bind_param(':medicationdetails', $medicationdetails);
$stmt->execute();
$stmt->close();} ?>
I have previously tried a variance using:
<?php
$stmt = $con->prepare("INSERT INTO medical ('forename', 'surname', 'dob', 'address', 'college', 'emergency_name', 'emergency_number', 'condition', 'condition_details', 'medication', 'medication_details') VALUES (?,?,?,?,?,?,?,?,?,?,?)")
$stmt->bind_param('sssssssssss', $first...);
?>
In both instances I get an error message that the $stmt variable doesn't exist.
Any suggestions as to where I'm going wrong?
Column names should be escaped with backticks, not single-quotes. Also, you can't use named parameter bindings.
Try
$stmt = $con->prepare("INSERT INTO medical (`forename`, `surname`, `dob`, `address`, `college`, `emergency_name`, `emergency_number`, `condition`, `condition_details`, `medication`, `medication_details`) VALUES (?,?,?,?,?,?,?,?,?,?,?)")
if (!$stmt)
{
echo $con->error;
}
Maybe you should try using this SQL syntax instead:
$stmt = $con->prepare("INSERT INTO medical VALUES (:forename, :surname, :dob, :address, :college, :emergencyname, :emergencynumber, :condition, :conditiondetails, :medication, :medicationdetails)");
$stmt->bind_param(':forename', $first);
$stmt->bind_param(':surname', $last);
$stmt->bind_param(':dob', $dob);
$stmt->bind_param(':address', $address);
$stmt->bind_param(':college', $college);
$stmt->bind_param(':emergencyname', $emergname);
$stmt->bind_param(':emergencynumber', $emergnumber);
$stmt->bind_param(':condition', $condition);
$stmt->bind_param(':conditiondetails', $conditiondetails);
$stmt->bind_param(':medication', $medication);
$stmt->bind_param(':medicationdetails', $medicationdetails);
$stmt->execute();
Or try:
$stmt = $con->prepare("INSERT INTO medical VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssssssss', $first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $tenth, $eleventh);
Meaning, without no Use-Fields declaration in your INSERT statement.