Inserting into MySQL database, query not running - php

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.

Related

INSERT into mysql DATABASE Prepared Statments

Can anybody see why this is not inputting into my database..
I did have it working, but now i got the error on mysql A form on this field has more than 1000 fields, but none of them do....
here is the prep statment
$db = new PDO("mysql:host=localhost;dbname=class2", 'root', '');
$query="INSERT INTO `testdata` (`1st name`, `2nd name`, `title`, `info`, `location`, `phone`, `postcode`, `image`, `image2`, `image3`, `image4`, `image5`, `price`, `catagory`, `cond`, `delivery`, `email`, `username`, `youtubevideo`, `paypal`, `facebook`, `twitter`, `feedbackscore`)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stat=$db->prepare($query);
$stat->execute(array("$firstname","$lastname","$sellingtitle","$sellinginfo","$town","$phone1","$postcode","$i0url","$i1url","$i2url","$i3url","$i4url","$price","$catagory","$cond","$delivery","","$sellername","$youtubeurl","$paypal","$facebook","$twitter","feedbackscore"));
Your PDO is not prepared correctly.
$database = new PDO("mysql:host=localhost;dbname=class2", 'root', '');
$query = "UPDATE users SET first_name = :first_name, last_name = :last_name
WHERE user_id = :user_id";
$update = $database->prepare($query);
$update->execute([
':first_name' => $_POST['firstname'],
':last_name' => $_POST['lastname'],
':user_id' => $_SESSION['user_id']
]);
$update->fetch();
With PDO you define the keys of the values in the prepare string like :first_name.
So then in the execute function's array, you define the values of these keys.
Hope it helps.

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.

Database error. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax

I am getting this error:
An error occured: Database error. 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 '#gmail.com, salt = , iteration = 12, method = blowfish, person_id' at line 1
Here is the code:
$data_con = new data_abstraction;
$data_con->execute_query("INSERT into `USER` SET `username` = $user, `password` = $phsh, `email` = $email, `salt` = $salt, `iteration` = $new_iteration, `method` = $new_method, `person_id` = $result2, `role_id` = $result4, `skin_id` = $result5");
Edit:
I already used prepared the query, used parameterized statements and bind the parameters. The error has gone but the details I want to be inserted into the table are not added.
Here is my code:
if(!($sql = $link->prepare("INSERT into `USER` SET
`username` = ?,
`password` = ?,
`email` = ?,
`salt` = ?,
`iteration` = ?,
`method` = ?,
`person_id` = ?,
`role_id` = ?,
`skin_id` = ?"))){
echo "SQL Query Preparation has failed";
}
if(!($sql->bind_param("ssssisiii", $user, $phsh, $email, $new_salt, $new_iteration, $new_method, $result2, $result4, $result5))){
echo "Parameter Binding failed";
}
if(!($sql->execute())){
echo "MySQL Query Execution has failed";
}
All text data must be wrapped in quotes in a concatenated query like this. It is also legal to wrap integers in quotes so its safer to do both like this
$data_con = new data_abstraction;
$data_con->execute_query("INSERT into `USER` SET
`username` = '$user',
`password` = '$phsh',
`email` = '$email',
`salt` = '$salt',
`iteration` = '$new_iteration',
`method` = '$new_method',
`person_id` = '$result2',
`role_id` = '$result4',
`skin_id` = '$result5'");
It would be better to use a parameterised query like this and then bind the values
$sql = "INSERT into `USER` SET
`username` = ?,
`password` = ?,
`email` = ?,
`salt` = ?,
`iteration` = ?,
`method` = ?,
`person_id` = ?,
`role_id` = ?,
`skin_id` = ?");
And then prepare the query and bind the values to the ? using bind_param
This will also protect you from SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
$email contains special character so quote email column value email = '$email'
You need to wrap each $variable in single quotes ''. BTW, that is horrible code, unless the execute_query() method sanitizes those input variables. If it doesn't, you seriously need to take a look at parameterizing your queries. I'm assuming you use mysqli? If so, take a look here: http://php.net/manual/en/mysqli.prepare.php

How to insert an actual NULL value into a nullable column?

function save($gmt, $name, $address, $phone, $remark)
{
$query= "INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('$gmt', '$name', '$address', '$phone', '$remark')";
mysql_query($query);
}
Here, address, phone, and remark can be NULL. I need it to save NULL whenever the variable is set to NULL and the column is nullable, instead of inserting an empty string.
How can I insert NULL value into the database using PHP?
This is PHP solution, but you have to use mysqli because mysql deprecated, please read more about mysqli.
Also, you must consider SQL injection
function save($gmt, $name, $address, $phone, $remark)
{
if(empty($phone)){
$phone = 'NULL';
}else{
$phone = "'".$phone."'";
}
if(empty($remark)){
$remark = 'NULL';
}else{
$remark = "'".$remark."'";
}
$query= "INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('$gmt', '$name', '$address', $phone, $remark)";
mysql_query($query);
}
//tests
save("a", "b", "c", "", "")."<br>";
save("a", "b", "c", "d", "")."<br>";
save("a", "b", "c", "d", "e")."<br>";
/*
INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', NULL, NULL)
INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', 'd', NULL)
INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', 'd', 'e')
*/
?>
DEMO
Try switching to prepared statements (which as a bonus is less prone to SQL injections).
function save($gmt, $name, $address, $phone, $remark)
{
if(!isset($phone) || empty($phone)) { $phone = null; }
if(!isset($remark) || empty($remark) { $remark = null; }
$db = new PDO(...);
$stmt = $db->prepare("INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES (:gmt, :name, :address, :phone, :remark)");
$stmt->bindValue("gmt", $gmt, PDO::PARAM_STR);
$stmt->bindValue("name", $name, PDO::PARAM_STR);
$stmt->bindValue("address", $address, PDO::PARAM_STR);
$stmt->bindValue("phone", $phone, PDO::PARAM_STR);
$stmt->bindValue("remark", $remark, PDO::PARAM_STR);
$stmt->execute();
}
This will handle the null values correctly in MySQL
PHP doesn't print NULL - it is just an empty string. So in your example you will try to insert '', which in SQL again is an empty string.
You have to use NULL (without quotes).
And the best practice to achieve that is to use an ORM or a PHP framework with a database abstraction layer which does this for you.
Using ternary operator, you can also use this
$add = ($address == '' ? NULL : $address);
$phn = ($phone == '' ? NULL : $phone);
$rmk = ($remark == '' ? NULL : $remark);
fields can be NULL
-> qtd_aulas_previstas
-> qtd_aulas_dadas
$qtd_aulas_previstas = ( empty($qtd_aulas_previstas) ? 'NULL' : "'".$qtd_aulas_previstas."'");
$qtd_aulas_dadas = ( empty($qtd_aulas_dadas) ? 'NULL' : "'".$qtd_aulas_dadas."'");
//insere os dados na tabela
$inserir_tb = mysqli_query($conexao, "INSERT INTO tb_turma_bimestre VALUES('', '$cod_turma', '$cod_bimestre', $qtd_aulas_previstas, $qtd_aulas_dadas, '$data_abertura', '$data_encerramento', '$date_time', '$nome_login')")or die("Error2: " .mysqli_error($conexao));

PHP Prepared statements issue

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

Categories