PHP Prepared statements issue - php

I'm getting error message
Column 'fname' cannot be null
In fact it is not null. I think that there is something wrong with binding. Do I need to bind NOW() too?
$stmt = $db->prepare("INSERT INTO `users` (`fname`, `mname`, `lname`, `email`, `pass`, `reg_dt`) VALUES (?, ?, ?, ?, ?, NOW())") or die(htmlspecialchars($db->error));
$rc = $stmt->bind_param("sssss", $fname, $mname, $lname, $email, $pass) or die(htmlspecialchars($stmt->error));
??

Your schema probably has a NOT NULL attribute for fname, which is why you are getting the null error.
According to your code you appear to be binding the params correctly, did you test to see if $fname actually as a value?
An alternate construct, for the sake of clarity (personally I don't like the ?, ?, ? binding). Also, let me qualify the following code by saying that it's PDO, not mysqli, the OP didn't indicate which was being used, that that it is just for demonstrative purposes only:
$sql =
"INSERT INTO `users` " .
"SET fname = :fname, " .
"mname = :mname, " .
"lname = :lname, " .
"email = :email, " .
"pass = :pass, " .
"reg_dt = NOW()";
$stmt = $db->prepare($sql);
$stmt->bindValue(':fname', $fname, PDO::PARAM_STRING);
$stmt->bindValue(':mname', $mname, PDO::PARAM_STRING);
$stmt->bindValue(':lname', $lname, PDO::PARAM_STRING);
$stmt->bindValue(':email', $email, PDO::PARAM_STRING);
$stmt->bindValue(':pass', $pass, PDO::PARAM_STRING);
Or if you don't prefer the construct, you may consider adding a CURRENT_TIMESTAMP attribute to your timestamp column:
`reg_dt` timestamp NULL default CURRENT_TIMESTAMP

Related

Can a prepared statement hold multiple queries in php

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.

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.

Insert into mysql with php

I have this piece of code, my user_account table gets populated but I am not getting anything inside my donor table. Can someone please tell me what could be the problem ? Thanks!
$stmt = mysqli_prepare($conn, "INSERT INTO user_account(username, password) VALUES (?, ?);") or die("Can't prepare user_account query: " . mysqli_error($conn));
mysqli_stmt_bind_param($stmt, "ss", $_POST['user'], $_POST['psw']);
mysqli_execute($stmt);
$stmt2 = mysqli_prepare($conn, "
INSERT INTO donor (user_id, blood_id, first_name,last_name,email_add,gender, birthday, telephone, city, last_donation)
SELECT LAST_INSERT_ID(), b.blood_id, ?, ?, ?, ?, ?, ?, ?, ?
FROM blood_type AS b
WHERE b.Blood_group= ?") or die ("Can't prepare donor query: " . mysqli_error($conn));
mysqli_stmt_bind_param($stmt2, "sssssssss", $_POST['fname'], $_POST['lname'], $_POST['email'], $_POST['gender'], $_POST['Birthday'], $_POST['Telephone'], $_POST['city'], $_POST['lastdonation'], $_POST['bloodgroup']);
mysqli_execute($stmt2);

Inserting into MySQL database, query not running

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.

PHP connected to db can't use insert function

I've been sitting on the same small problem now for over 10 hours, so it's time to ask stackoverflow! I'm connected to the database but when calling mysqli_stmt_bind_param I get "invalid object or resource".
I've tried the insert statement in the console and it works fine..
<?php
$con=mysqli_connect("127.0.0.1:3306", "myUsername", "password");
mysqli_select_db($con, "webshop");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query= mysqli_stmt_init($con);
mysqli_stmt_prepare($query, "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($query, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($query))
{
mysqli_close($con);
}
?>
Thankful for any help at all!
You have to use the statement object returned by mysqli_stmt_prepare()
$stmt = mysqli_stmt_prepare($con, "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($stmt))
Also, the mysqli_stmt_init($con) call is not needed (I think).
mysqli_stmt_init is needed as you are accessing mysqli using the procedural style.
This returns an object of type mysqli_stmt, which then acts as a container for the query you are building. As such, you should pass this as the first parameter to mysqli_stmt_prepare, mysqli_stmt_bind_param and mysqli_stmt_execute.
So your code would look like:
<?php
$con=mysqli_connect("127.0.0.1:3306", "myUsername", "password");
mysqli_select_db($con, "webshop");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_stmt_init($con);
$query = "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($stmt))
{
mysqli_close($stmt);
}
?>
One, unrelated point - you appear to be requiring that your tel field (which I presume to be a telephone number) is an integer. This might be a bad idea if you have to handle telephone numbers starting with 0 (common in the UK for example) at any point.

Categories