PDO is inserting "null" for empty values - php

I am using PDO for writing to sqlite database.
// $dbo is an instance of PDO
$query = "INSERT INTO items (id, name, rank) VALUES (:id, :name, :rank)";
$statement = $dbo->prepare($query);
$values = array('id' => 1, 'name' => 'Some Name', 'rank' => '');
$statement->execute($values);
$values = array('id' => 1, 'name' => 'Some Name', 'rank' => NULL);
$statement->execute($values);
After executing any of these, I expect "rank" to be an empty string or even a NULL is acceptable.
But what I get in the database is 'null', yes a string 'null' value, not the real NULL.
Could not find any solution after several attempts.

Try sending NULL directly in this line
$values = array('id' => 1, 'name' => 'Some Name', 'rank' => NULL);

Related

Create Main Array that includes multiple child array

How Can I Create a main array that includes multiple child array And be in the form of Jason and I want to add the child Array to main array in the Loop
MainArray=[
array1=[{fname:asdada,lastname:sdsadasda}];
array2=[{fname:asdada,lastname:sdsadasda}];
array3=[{fname:asdada,lastname:sdsadasda}];
];
echo MainArray[1]->fname;
Please see the following pseudo code below:
pseudo code
You should really look into a basic php tutorial.
This is how you do it.
$mainArray = [
'array1' => ['fname' => 'asdada', 'lastname' => 'sdsadasda'],
'array2' => ['fname' => 'asdada', 'lastname' => 'sdsadasda'],
'array3' => ['fname' => 'asdada', 'lastname' => 'sdsadasda']
];
echo $mainArray['array1']['fname'];
Or use the long notation if you have an older version of php or want backwards compatibility.
$mainArray = array(
'array1' => array('fname' => 'foo', 'lastname' => 'bar'),
'array2' => array('fname' => 'lorem', 'lastname' => 'ipsum'),
'array3' => array('fname' => 'test', 'lastname' => 'example')
);
echo $mainArray['array1']['fname'];
Explanation:
The php variable sigil is $. This means that in order to access a variable or assign something to a variable, you use $mainArray. See more on variables in the documentation.
The php array can be used in two different notations. Either array(...) or, from php 5.4 upwards, [...]. Other than the opening and closing parts, they are identical. You don't use : or = to assign individual values inside an array declaration. For this you use the => operator. Each element in an array is separated by a comma (,).
E.g.
$mainArray = array(
'A' => 1,
'B' => 2
];
Arrays in Php can be either associative or numerical. What you probably want is that your outer array is numerical, meaning you can access it using $mainArray[1], and your inner array is associative. For numerical arrays, you don't specify a key yourself, so there is no need for the =>.
$mainArray = array(
array(),
array(),
array()
);
And with associative sub arrays this becomes:
$mainArray = array(
array('firstname' => 'foo', 'lastname' => 'bar'),
array('firstname' => 'test', 'lastname' => 'example'),
array('firstname' => 'lorem', 'lastname' => 'ipsum')
);
In order to access the firstname key of the first child array in this multilevel array structure, you do:
$mainArray[0]['firstname']
E.g. (if you want to echo it to the standard output)
echo $mainArray[0]['firstname'];
Please note that numerical arrays in php start counting on 0, as in most other programming languages. And please note that the key in the associative array is a string, and as such must be surrounded with either ' or ".
I can recommend you search for a php beginner's tutorial and try to write and execute the examples yourself, to get a better grasp of php. If you need somewhere to run your php examples, I can recommend you try an online php environment such as PHPFiddle.
Update on adding values:
You can add more key=>value pairs to an associative array or add more values to a numerical array afterwards in much the same way as you would access or assign to it.
First, let's add a value to a numerical array. You do this by adding [] to the end of your variable when assigning. This means that what you assign will be added as a new numerical value to the end of your array.
$numericalArray = array(
7,
8,
6,
12,
'B'
);
$numericalArray[] = 'C';
// Results in the array: array(7, 8, 6, 12, 'B', 'C')
And in order to add a new key => value pair to an associative array, you just add it using the new key, e.g.
$assoc = array(
'firstname' => 'Testy',
'lastname' => 'McTestface'
);
$assoc['middlename'] => 'Tester';
So to add a new fname-lastname pair to the mainArray, you would do:
$mainArray = array(
array('fname' => 'foo', 'lastname' => 'bar'),
array('fname' => 'test', 'lastname' => 'example'),
array('fname' => 'lorem', 'lastname' => 'ipsum')
);
$mainArray[] = array('fname' => 'new name', 'lastname' => 'new last name');
If you want to do this in a loop, you will use the for, foreach, while or do while structures.
E.g.
$mainArray = array(
array('fname' => 'foo', 'lastname' => 'bar'),
array('fname' => 'test', 'lastname' => 'example'),
array('fname' => 'lorem', 'lastname' => 'ipsum')
);
for ($i = 0; $i < 3; ++$i) {
$mainArray[] = array('fname' => 'new name ' . $i, 'lastname' => 'new last name ' . $i);
}
echo json_encode($mainArray, JSON_PRETTY_PRINT|JSON_UNESPACED_UNICODE|JSON_UNESCAPED_SLASHES), PHP_EOL;
// [
// {'fname': 'foo', 'lastname': 'bar'},
// {'fname': 'test', 'lastname': 'example'},
// {'fname': 'lorem', 'lastname': 'ipsum'},
// {'fname': 'new name 0', 'lastname': 'new last name 0'},
// {'fname': 'new name 1', 'lastname': 'new last name 1'},
// {'fname': 'new name 2', 'lastname': 'new last name 2'},
// ]

Merge arrays by suffix of keys PHP

I have two arrays, that I want to merge as one according to keys suffix.
$keys = array(
'staff_first_name' => NULL,
'staff_last_name' => NULL,
'staff_years' => NULL
);
$submitted_values = array(
'first_name' => 'jon',
'last_name' => 'doe',
'years' => 5
);
I understand I could use a function like shown here and modify it.
But is there a native php function that will accomplish this. I attempted to use array_merge_recursive but after reviewing the documentation It will not do what I need it to.
$wanted_array = array(
'staff_first_name' => 'jon',
'staff_last_name' => 'doe',
'staff_years' => 5
);
If you know the two arrays are the same size, and in the same order, you can use array_combine with array_keys.
$wanted_array = array_combine(array_keys($keys), $submitted_values);
Because it's a suffix that is the same on each key we don't need to worry about it.
If we ksort the arrays they should both be sorted the same because the suffix is the same on all in key array.
$keys = array(
'staff_first_name' => NULL,
'staff_last_name' => NULL,
'staff_years' => NULL
);
$values = array(
'years' => 5,
'first_name' => 'jon',
'last_name' => 'doe',
);
ksort($values);
ksort($keys);
Var_dump(array_combine(array_keys($keys), $values));
I intentionally placed years first to show that it works.
https://3v4l.org/cBNhk
If you need to reduce the $_POST to only these array items to be able to combine them you can use a combination of preg_grep, array_flip, array_values and array_intersect_key to filter out the wanted items from the array.
$val = preg_grep("/first_name|last_name|years/",array_values(array_flip($values)));
$values = Array_intersect_key($values, array_flip($val));
ksort($values);
ksort($keys);
Var_dump(array_combine(array_keys($keys), $values));
I added some extra items to simulate a larger mixed $_POST array.
https://3v4l.org/a3ju1
This is one of those questions where I must implore the OP to rethink their process. It only complicates your code to introduce associative keys that do not instantly synchronize with your form field names. This is the best advice that I can give you: declare a whitelist of keys and assign default values to each, then filter, then replace.
Since your values are all null, your code can be made more DRY by calling array_fill_keys().
The following can be written as one line of code, but to show each step, I've printed the arrays to screen after each function call.
Code: (Demo)
$defaults = array_fill_keys(['first_name', 'last_name', 'years'], null);
var_export($defaults);
$_GET = [
'last_name' => 'doe',
'Hackers' => 'can be naughty',
'years' => 5
];
var_export($_GET);
$screened = array_intersect_key($_GET, $defaults);
var_export($screened);
$replaced = array_replace($defaults, $screened);
var_export($replaced);
Output:
array (
'first_name' => NULL,
'last_name' => NULL,
'years' => NULL,
)array (
'last_name' => 'doe',
'Hackers' => 'can be naughty',
'years' => 5,
)array (
'last_name' => 'doe',
'years' => 5,
)array (
'first_name' => NULL,
'last_name' => 'doe',
'years' => 5,
)
...p.s. makes sure that you use prepared statements with placeholders if you are sending any of the values to the database.

PHP/Phinx - Inserting Longitude/Latitude causes PDO MySQL geometry object error

I'm attempting to create a CitySeeder using Phinx. But I'm getting the following error:
[PDOException]
SQLSTATE[22003]: Numeric value out of range: 1416 Cannot get geometry object from data you send to the GEOMETRY field
Here is my seeders/CitySeeder.php class. The geo_coords field uses a POINT datatype:
<?php
use Phinx\Seed\AbstractSeed;
class CitySeeder extends AbstractSeed
{
public function run()
{
$data = [
[
'name' => 'birmingham',
'geo_coords' => 'POINT(0 0)'
],
[
'name' => 'london',
'geo_coords' => 'POINT(0 0)'
],
[
'name' => 'liverpool',
'geo_coords' => 'POINT(0 0)'
],
[
'name' => 'manchester',
'geo_coords' => 'POINT(40 -100)'
],
];
$cityTable = $this->table('city');
$cityTable->insert($data)->save();
}
}
Which is strange because if I enter that manually into the database it works.
Does the longitude/latitude have to be formatted in a certain way? I've tried using an array, and a space separated long lat format but I still get the same error. I've even went as far as looking through the source code but can not find anything useful.
Any help would be much appreciated.
Edit
I've inspected the code from the Phinx library where the error is happening:
public function insert(Table $table, $row)
{
$this->startCommandTimer();
$this->writeCommand('insert', array($table->getName()));
$sql = sprintf(
"INSERT INTO %s ",
$this->quoteTableName($table->getName())
);
$columns = array_keys($row);
$sql .= "(". implode(', ', array_map(array($this, 'quoteColumnName'), $columns)) . ")";
$sql .= " VALUES (" . implode(', ', array_fill(0, count($columns), '?')) . ")";
$stmt = $this->getConnection()->prepare($sql);
$stmt->execute(array_values($row));
$this->endCommandTimer();
}
The data from array_values($sql) at the point of failure is:
array(2) {
[0]=>
string(10) "birmingham"
[1]=>
string(26) "POINT(0 0)"
}
And the query after $sql is set:
string(55) "INSERT INTO `city` (`name`, `geo_coords`) VALUES (?, ?)"
When doing the following after prepare(): die(var_dump($stmt->debugDumpParams()));:
SQL: [55] INSERT INTO `city` (`name`, `geo_coords`) VALUES (?, ?)
Params: 0
NULL
Logging the MySQL queries shows the following:
2016-12-12T12:53:12.721287Z 12 Query INSERT INTO `city` (`name`, `geo_coords`) VALUES ('birmingham', 'POINT(0, 0)')
I believe this is incorrect because the POINT is being inserted as a string?
Solved the problem using the following:
<?php
use Phinx\Seed\AbstractSeed;
class CitySeeder extends AbstractSeed
{
public function run()
{
$data = [
[
'name' => 'birmingham',
'geo_coords' => [0, 0],
],
[
'name' => 'london',
'geo_coords' => [0, 0],
],
[
'name' => 'liverpool',
'geo_coords' => [0, 0],
],
[
'name' => 'manchester',
'geo_coords' => [0, 0],
],
];
$conn = $this->getAdapter()->getConnection();
$sth = $conn->prepare('INSERT INTO city (`name`, `geo_coords`) VALUES (?, POINT(?, ?))');
foreach($data as $key => $val)
{
$sth->execute([
$val['name'],
$val['geo_coords'][0],
$val['geo_coords'][1]]
);
}
}
}

Laravel database insert query

I'm trying to do simple insertion in database and im getting the following error
call_user_func_array() expects parameter 1 to be a valid callback, no
array or string given
The insertion code look like this
DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
It's a basic query for laravel, but it won't work why?
DB::table('users')->insert(
array(
'id' => '1',
'name' => 'Dayle'
)
);
or
$values = array('id' => 1,'name' => 'Dayle');
DB::table('users')->insert($values);
But why are you inserting an ID? Should this not be an auto incremented value?
$user['id'] = 1;
$user['name'] = 'dale';
DB::table('users')->insert($user);
You can make simple like this
$val={
'id_user' => '< ID_USER >',
'title' => '< TITLE >',
'body' => '< BODY >',
}
Forum::create($val);
And its work

SQL Results as PHP Array

I am trying to solve this. Maybe this is absolutly incorrect, I need some help.
I have a table like this:
INSERT INTO `municipios` (`id`, `provincia`, `municipio`) VALUES (1, 1, 'Alegría-Dulantzi'), (2, 1, 'Amurrio'), (3, 1, 'Añana'), (4, 1, 'Aramaio'), (5, 1, 'Armiñón'),
And this is my handler:
$query = "SELECT * FROM municipios WHERE provincia='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$groups = array(
$row{'id'} => array(
'name' => $row{'municipio'},
'description' => 'Agrupación electoral de ' . $row{'municipio'},
'status' => 'public',
'enable_forum' => 1,
),
);
}
With this I got just the last result. I have tried another options, but doesn´t work.
Something like this should solve your issue:
$groups[] = array(
$row['id'] => array(
'name' => $row['municipio'],
'description' => 'Agrupación electoral de ' . $row['municipio'],
'status' => 'public',
'enable_forum' => 1,
),
);
However, may i suggest your use PDO. There is a pretty good article http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ that should get you going in the right direction.
Is this an issue with the way you're appending the groups array? I think your overwriting the array every time u set a value. Try using array_push() to append to groups.
Let us know of that helps!
array_push()
http://php.net/manual/en/function.array-push.php

Categories