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]]
);
}
}
}
Related
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);
I have a many to many relationship between two tables: atentions and procedimientos. it looks like this
As you can see, my pivot table has 2 extra columns, cantidad, and descuento, along with the keys from both tables.
However, when i try to insert data in that table, i get the error message ErrorException
Array to string conversion and if i format those values using json_encode, i get the following
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '["1","1"]' for column `dentalg`.`atencion_procedimientos`.`cantidad` at row 1 (SQL: insert into `atencion_procedimientos` (`atencion_id`, `cantidad`, `created_at`, `descuento`, `procedimientos_id`, `updated_at`) values (11, ["1","1"], 2020-05-06 02:19:20, ["1","1"], 1, 2020-05-06 02:19:20), (11, ["1","1"], 2020-05-06 02:19:20, ["1","1"], 2, 2020-05-06 02:19:20))
This is my store function
public function store(Request $request)
{
//
$this->validate($request,[
'asunto' => 'required',
'cantidad' => 'required',
'descuento' => 'required',
'total_pago' => 'required'
]);
if(Auth::user()->role_id ==1 or Auth::user()->role_id==2){
$atencion = new Atencion();
$atencion->doctor_id = Auth::id();
$atencion->pacientes_id = $request->paciente_id;
$atencion->asunto = $request->asunto;
$atencion->tipo_pago = 0; //Tratar de Modificar
$atencion->estado_pago = 0;
$atencion->observaciones = $request->observaciones;
$atencion->total = $request->total_pago;
$atencion->save();
$atencion->procedimientos()->attach($request->procedimientos_id,[
'cantidad' => $request->cantidad,
'descuento' => $request->cantidad,
]);
Toastr::success('Tratamiento añadido con éxito','success');
return redirect()->route('admin.Atenciones.index');
} else {
Toastr::error('You are not authorized to do this operation','Error');
return redirect()->back();
}
Models
public function procedimientos(){
return $this->belongsToMany('App\Procedimientos')->withPivot('cantidad', 'descuento')->withTimestamps();
}
and
public function atenciones(){
return $this->belongsToMany('App\Atencion')->withPivot('cantidad', 'descuento')->withTimestamps();
}
So I have been doing my research and no method seems to parse my file correctly. I have tried these two codes, my data is being inserted into sql however it is inserted 3 times with the first insertion being fine while the other 2 are blank. Here is my JSON file and code:
JSON:
[
{
"Comments": {
"Manufacturer": "--E",
"Model": "----- ----- ----",
"BIOSFamily": "---",
"BIOSDate": --/--/---8",
"SerialNumber": "---------"
}
},
{
"#ComputerSystem.v1-----------ystem": {
"/redfish/v1/Systems/1/": {
"AssetTag": " ",
"Bios": {
"#odata.id": "/redfish/v1/systems/1/bios/"
},
"BiosVersion": "U----------------)",
"Boot": {
"BootSourceOverrideMode": "-----y",
"BootSourceOverrideTarget": "None",
"BootSourceOverrideEnabled": "Disabled",
"BootSo-----------arget#Redfish.AllowableValues": [
"None",
"Cd",
"Hdd",
"Usb",
"Utilities",
"Diags",
"BiosSetup",
"Pxe",
"UefiShell"
]
Code:
<?php
$connect = mysqli_connect("reserve1",
"root", "","server_31");
$filename = "-----.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO servers (Model,
Manufacturer, BIOSFamily,
BIOSDate,
SerialNumber) VALUES
('".$row["Comments"]["Model"]."' ,
'".$row["Comments"]
["Manufacturer"]."',
'".$row["Comments"]
["BIOSFamily"]."','".$row["Comments"]
["BIOSDate"]."','".$row["Comments"]
["SerialNumber"]."')";
mysqli_query($connect, $sql);
}
echo "Data in";
?>
ERROR:" Notice: Undefined index: Comments "
other forloops i have tried are:
foreach($data as $Comments)
{
$sql =" INSERT INTO
'servers'('Manufacturer','Model',
'BIOSFamily','BIOSDate',
'SerialNumber'), VALUES('{$Comments-
>Manufacturer}', '{$Comments-
>Model}',
'{$Comments->BiosFamily}',
'{$Comments->BiosDate}',
'{$Comments-
>SerialNumber}')";
}
ERROR:" Notice: Trying to get property of non-object in"
To reiterate: the first method does get my info onto sql but does so 3 times with the last 2 entries being blank. The second method does not insert anything into my table.
EDIT:
so i tried vardump, using the file itself all i got was NULL, copy and pasting the contents and labeling it $json= ' content ' in the script i get..
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:16:
array (size=1)
0 =>
object(stdClass)[1]
public 'Comments' =>
object(stdClass)[2]
public 'Manufacturer' => string 'HPE' (length=3)
public 'Model' => string '-------------' (length=20)
public 'BIOSFamily' => string '---' (length=3)
public 'BIOSDate' => string '--/--/----' (length=10)
public 'SerialNumber' => string '-------' (length=10)
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:17:
array (size=1)
0 =>
array (size=1)
'Comments' =>
array (size=5)
'Manufacturer' => string '---' (length=3)
'Model' => string '------ ----------' (length=20)
'BIOSFamily' => string '---' (length=3)
'BIOSDate' => string '--/--/----' (length=10)
'SerialNumber' => string '-------' (length=10)
Simply index in your foreach loop the first item since $array object maintains Comments only in first position. See 0 index from var_dump output:
array (
0 =>
array (
'Comments' =>
array (
'Manufacturer' => '--E',
'Model' => '----- ----- ----',
'BIOSFamily' => '---',
'BIOSDate' => ' --/--/-- - 8 ',
'SerialNumber' => '---------',
),
),
1 =>
array (
'#ComputerSystem.v1-----------ystem' =>
...
Therefore, iterate through the Comments array and use parameterization for readability:
$connect = new mysqli($servername, $username, $password, $dbname);
// PREPARED STATEMENT
$sql = "INSERT INTO servers (Model, Manufacturer, BIOSFamily, BIOSDate, SerialNumber)
VALUES(?, ?, ?, ?, ?)";
// INDEX FIRST ITEM AT 0
foreach($array[0] as $row) {
$stmt = $connect->prepare($sql);
// BIND PARAMETERS (NO COMMENTS INDEX)
$stmt->bind_param("sssss", $row["Model"],
$row["Manufacturer"],
$row["BIOSFamily"],
$row["BIOSDate"],
$row["SerialNumber"]);
// EXECUTE STATEMENT
$result = $stmt->execute();
}
Hello I try with PDO to insert data to Sqlite, i have tried many ways, but I always get following errors: Call to a member function bindParam() on boolean.
I see also the bindParam() or bindValue return false if an error exist. But I don't find an error.
thx in advance
function insertCostumers(){
$costumers = 'INSERT IGNORE INTO costumers(first_name,last_name,age)
VALUES(:first_name,:last_name,:age)';
$stmt = $this->pdo->prepare($costumers);
$data = [['firstName' => 'Hans',
'lastName' => 'Meier',
'age' => 32],
['firstName' => 'Anna',
'lastName' => 'Mueller',
'age' => 35],
['firstName' => 'Steffi',
'lastName' => 'Gygax',
'age' => 67]];
$stmt->bindParam(
':first_name', $firstName,
':last_name', $lastName,
'age', $age);
foreach ($data as $d) {
// Set values to bound variables
$firstName = $d['firstName'];
$lastName = $d['lastName'];
$age = $d['age'];
// Execute statement
$stmt->execute();
}
die('hello');
}
require "SQLiteConnection.php";
require "SQLiteCreateTable.php";
$sqlite = new SQLiteCreateTable((new SQLiteConnection())->connect());
// create new tables
$sqlite->createTables();
$sqlite->insertCostumers();
$tables = $sqlite->getOrderList();
require "index.view.php";
#SebastianBrosch Thats the Create Statement.
public function createTables() {
$commands = ['CREATE TABLE IF NOT EXISTS costumers (
costumer_id integer PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
age integer NOT NULL
)',
'CREATE TABLE IF NOT EXISTS orders (
order_id integer PRIMARY KEY,
order_nr integer NOT NULL,
costumer_id integer,
FOREIGN KEY (costumer_id) REFERENCES costumers (costumer_id)
ON DELETE CASCADE ON UPDATE NO ACTION)'];
// execute the sql commands to create new tables
foreach ($commands as $command) {
$this->pdo->exec($command);
}
}
The variable $stmt is not a PDOStatement object. It is a boolean value (in this case false).
Your INSERT statement is not valid. Try the following instead (missing OR):
$costumers = 'INSERT OR IGNORE INTO costumers(first_name, last_name, age)
VALUES(:first_name, :last_name, :age)';
You can use the methods PDO::errorInfo and PDO::errorCode to get further information.
$costumers = 'INSERT OR IGNORE INTO costumers(first_name,last_name,age)
VALUES(:first_name,:last_name,:age)';
$stmt = $this->pdo->prepare($costumers);
if ($stmt === false) {
echo $this->pdo->errorCode().': '.$this->pdo->errorInfo();
}
You also use $firstName and $lastName before init:
function insertCostumers() {
$costumers = 'INSERT OR IGNORE INTO costumers(first_name, last_name, age)
VALUES(:first_name, :last_name, :age)';
$stmt = $this->pdo->prepare($costumers);
$data = [['firstName' => 'Hans',
'lastName' => 'Meier',
'age' => 32],
['firstName' => 'Anna',
'lastName' => 'Mueller',
'age' => 35],
['firstName' => 'Steffi',
'lastName' => 'Gygax',
'age' => 67]];
foreach ($data as $d) {
$firstName = $d['firstName'];
$lastName = $d['lastName'];
$age = $d['age'];
$stmt->bindParam(':first_name', $firstName, PDO::PARAM_STR);
$stmt->bindParam(':last_name', $lastName, PDO::PARAM_STR);
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
$stmt->execute();
}
}
To make sure the combination of first_name and last_name is unique, you need to add a UNIQUE constraint to your table costumers. Use the following CREATE TABLE statement:
CREATE TABLE IF NOT EXISTS costumers (
costumer_id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
age INTEGER NOT NULL,
UNIQUE (first_name, last_name)
);
You can see the difference with and without the UNIQUE constraint on these following demo:
http://sqlfiddle.com/#!7/79b1c/1/1
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