Set a default value for INSERT statement PHP - php

I know this should be a simple question, i have the following insert statement which is inserting values captured via a form, all works well but i would also like to add a default value to a column not on my form(lets say language for example), i don't want to add the default value via the database, as i have two forms that are coming together to the one table.
$stmt = DB::query(Database::INSERT,
'INSERT INTO `my_products` (`first_name`, `initial`, `last_name`, `street`)
VALUES (:first_name, :initial, :last_name, :street)');
$stmt->param(':first_name', $post['first_name']);
$stmt->param(':initial', $post['initial']);
$stmt->param(':last_name', $post['last_name']);
$stmt->param(':street', $post['street']);
Is there a way to specify a default value via the above?

What's wrong with this?
$stmt = DB::query(Database::INSERT,
"INSERT INTO `my_products` (`first_name`, `initial`, `last_name`, `street`, `myColumn`)
VALUES (:first_name, :initial, :last_name, :street, 'my default value')");
Or possibly:
$stmt = DB::query(Database::INSERT,
'INSERT INTO `my_products` (`first_name`, `initial`, `last_name`, `street`, `myColumn`)
VALUES (:first_name, :initial, :last_name, :street, :my_column)');
...
$stmt->param(':my_column', 'my default value');

You could use my tiny library ValueResolver in this case, for example:
$stmt->param(':my_column', ValueResolver::resolve($post['first_name'], 'default')); // returns 'default' if $post['first_name'] is empty
and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;
There are also ability to typecasting, for example if your variable's value should be integer, so use this:
$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)
Check the docs for more examples

Related

Why deos PDO SELECT Work but BASIC INSERT fails?

I have connected to the db and able to update a record.
I have a variable named "action" that is either "update" or "add".
I use it in a switch statement to set my query to either "SELECT" or "INSERT".
SELECT statement works.
INSERT statement does not.
I get this error on $pdo->execute($data).
PHP Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in ...
PDOStatement->execute(Array)
The error is thrown by the PDOStatement
Here is what I have tried, seems pretty straight-forward, but i'm struggling with it.
$data = [
'firstName'=> $firstName,
'lastName'=> $lastName,
'badge'=> $badge,
'department'=> $department,
'image'=> $image,
'active'=> $active,
'stars'=> $stars,
'email'=> $email,
'primary_key'=> $primaryKey,
];
$sql = "INSERT INTO `team`
(`primary_key`,`firstName`, `lastName`, `badge`, `department`, `image`, `active`, `stars`, `email`)
VALUES
(NULL, :firstName, :lastName, :badge, :department, :image, :active, :stars, :email)";
$pdo->prepare($sql);
$pdo->execute($data); <- error is here
When I simply echo my $data array to see if there is something odd. I don't see anything based off all the sites, I've read.
//$data array DATA
primary_key =
firstName = test
lastName = test
badge = 9000
department = marketing
image = 9000.jpg
active = 1
stars = 0
email = tester#test.com
primary_key in db is auto-increment
primary_key is $_post[] on update query and NULL insert query (auto increment db column)
Any errors that would prevent this INSERT query from working that you can see? I'm stuck. I know it the array has 9 variables, there are 9 fields to insert, and 9 values listed.
I know it the array has 9 variables, there are 9 fields to insert, and 9 values listed.
Count the parameters. There are 8 of them. The array includes a value called primary_key for which there is no parameter in the query.
primary_key in db is auto-increment
Then don't insert a value for it:
$sql = "INSERT INTO `team`
(`firstName`, `lastName`, `badge`, `department`, `image`, `active`, `stars`, `email`)
VALUES
(:firstName, :lastName, :badge, :department, :image, :active, :stars, :email)";
And remove primary_key from the $data array.

insert data by GET

I want insert data by GET in my sql but I can not insert data
<?php
include("config.php");
$f=$_GET["first_name"];
$l=$_GET["last_name"];
$e=$_GET["email"];
$m=$_GET["mobile"];
$b=$_GET["birthday"];
$g=$_GET["gender"];
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES ('$f', '$l', '$e', '$m', '$b', '$g')";
mysqli_query($insert);
?>
I try insert data by this link :
http://localhost:8888/restfull/insert.php?f=hayoo
It's been a long time since I have used mysqli the code below should most likely run though. As others have mentioned never bind unsanitized data (Even if you think you trust the data it's safe to use prepared statements still).
<?php
//Create you db connection
$conn = new mysqli('server', 'user', 'password', 'databasename');
//Create insert statement. Never concat un-sanitized data in statements
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
//Values corespond to ? except the first param which represents format of expected data. "s" stands for string
$stmt->bind_param(
'ssssss',
$_GET["first_name"],
$_GET["last_name"],
$_GET["email"],
$_GET["mobile"],
$_GET["birthday"],
$_GET["gender"]
);
$stmt->execute();
Your url would look like this:
http://localhost:8888/restfull/insert.php?first_name=john&last_name=Doe&email=test#test.com&mobile=0&birthday=May&gender=male
Make sure if you are putting the url above in some type of form you correctly url encode values (I notice many of the values you are collecting will like require it slashes etc).

Why the SQL query is not working after addition of two new fields to the query?

I've following SQL query which is working absolutely fine .
$sql = "INSERT INTO user_login (user_id, email, password, token)
VALUES ($user_id, '$email', '$user_password', '$token')";
Now I've added two new fields to the respective table called 'token_creation_time' and 'token_last_accessed_time'. These fields will contain the current time values(i.e. UNIX Time stamp values). For this purpose I used time() function from PHP in the SQL query as follows but it didn't work. I don't know where I'm making a mistake.
$sql = "INSERT INTO user_login (user_id, email, password, token, token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', time(), '')";
The last two field's structure in MySQL DB is as follows :
Name : token_creation_time
Type : int(10)
Collation :
Attributes :
Null : No
Default : None
Extra :
Name : token_last_accessed_time
Type : int(10)
Collation :
Attributes :
Null : No
Default : None
Extra :
In my query I want to insert the current time stamp value only into the field 'token_creation_time'.
Thanks.
Just change the Null:No to Null:Yes,it should work
Name : token_last_accessed_time
Type : int(10)
Collation :
Attributes :
Null : Yes
Default : None
Extra :
I had encountered same error in postgresql when i try to insert an empty string '' for timestamps, so i use nullif function to overcome this:
NULLIF(?, '')
i think mysql has same function
AND make sure your column is nullable
You cannot use php time() function inside query.
Either concatenate this:
$sql = "INSERT INTO user_login (user_id, email, password, token, token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', ".time().", '')";
Or use mysql function UNIX_TIMESTAMP():
$sql = "INSERT INTO user_login (user_id, email, password, token, token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', UNIX_TIMESTAMP(),
'')";
You're inserting a literal string containing time() there.
$sql = "INSERT INTO user_login (user_id, email, password, token,
token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', time(), '')";
error here ^^^^^^
either a) use string concatenation to insert the actual timestamp.
$sql = "INSERT INTO user_login (user_id, email, password, token,
token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', " . time() . ", '')";
b) use pdo with a prepared statement (strongly preferred no matter what) to avoid sql injection attacks, or c) use mysql UNIX_TIMESTAMP() function instead of php time.
$sql = "INSERT INTO user_login (user_id, email, password, token,
token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', UNIX_TIMESTAMP(), '')";
a good way to debug this is to print the query statement out before you execute it, and then run it against the database directly, it will no doubt give you an error above shoving a string into an int or an unknown column
Change your table structure and set NULL attribute to Yes. It will work fine :)
Use now() replace with time() it may work.

Prevent SQL Injection on Insert, php

Can someone just save my life been reading for a few hours,
I followed this exactly:
http://docs.php.net/manual/en/pdo.prepared-statements.php
I got this working with sqli but i was told by the group that this was prome to sql injection so i'm trying to improve my code
Alot of the topics here are on SELECT
When I try this i get a blank page, i still haven't gotten apache to render errors that is a separate issue....
this is php:
$dbh = new PDO('mysql:host=localhost;dbname=table', $DBuser, $DBpswd );
$stmt = $dbh->prepare("INSERT INTO `sonyCES2013`.`registration` (`id`, `firstName`, `lastName`, `eMail`, `telephone`, `outlet`, `comfirm`, `boothTour`) VALUES (
:id,
:firstName,
:lastName,
:eMail,
:telephone,
:outlet,
:comfirm,
:boothTour
)");
$stmt->bindParam(':id', NULL);
$stmt->bindParam(':firstName', $fName);
$stmt->bindParam(':lastName',$lName);
$stmt->bindParam(':eMail', $eMail);
$stmt->bindParam(':telephone', $telephone);
$stmt->bindParam(':outlet', $outlet);
$stmt->bindParam(':comfirm',$comfirmation);
$stmt->bindParam(':boothTour', $dateFormatted);
$stmt->execute();
Empty string is not the same as NULL. Also you must pass variables to bindParam() by reference.
If you want to pass a NULL as a query parameter, use
$stmt->bindValue(':id', NULL);
Or you can make a dummy variable and pass that, and give PDO a hint that it's a NULL:
$null = null;
$stmt->bindParam(':id', $null, PDO::PARAM_NULL);
Or else just omit id from the column in your INSERT:
$stmt = $dbh->prepare("INSERT INTO `sonyCES2013`.`registration`
(`firstName`, `lastName`, `eMail`, `telephone`, `outlet`, `comfirm`,
`boothTour`) VALUES ...
The problem was I had set some attributes to NULL. Comfirm was an optional value on the form and if no one selected it, i made the variable NULL. I instead set them to an empty string ''. that solved the problem.

Zend_Db_Statement_Pdo->execute with expression in params

I try to execute insert statement with "on duplicate" part. As I know Zend doesn`t support this, so I use simple statement:
$sql = "INSERT INTO agent(`inn`, `name`, `created`) VALUES(:inn, :name, :created) ON
DUPLICATE KEY UPDATE `inn` = :inn, `name` = :name, `created` = :created";
$stmt = $this->db->prepare($sql);
$stmt->execute($bind);
Where $bind - is array:
array(
'inn'=>1234567890,
'name'=>'test user',
'created' = new Zend_Db_Expr('NOW()')
);
If I try this query through phpMyAdmin - all works fine,
but after script execution the "created" column value is '0000-00-00 00:00:00'.
WTF?
You can't use an expression as an argument to a placeholder in a prepared statement. It will be interpreted as a string. This has nothing to do with zend framework.
You can either created a formatted date string in php and use that, or use now() in the prepared statement like
VALUES(:inn, :name, NOW())
Another solution, if you need to sometimes supply a datetime, and sometimes use NOW(), is using conditionals to check for that specific case
VALUES(:inn, :name, IF(:created = 'NOW()', NOW(), :created))

Categories