I have the following SELECT query that looks to if there are records that meet the given criteria:
$stmt = $conn->prepare(' SELECT (`Active`)
FROM `Table1`
WHERE `Name` = ":name" AND Active <> Yes ');
$stmt->execute([
'name' => $_POST['name']
]);
If results of Active could either be a No or just no results. If the results are a No then the following query should run:
$stmt = $conn->prepare('UPDATE `Table1`
SET `active` = `Yes`
WHERE `Name` = `:name`');
$stmt->execute([
'name' => $_POST['name']
]);
If the results of the SELECT query does not find anything then the following query should run:
$stmt = $conn->prepare(' INSERT INTO `Table1` (`Name`,`Active`)
VALUES (:name, :active ) ');
$stmt->execute([
'name' => $_POST['name'],
'active' => $_POST['active']
]);
How can this conditional be written?
I specifically do not want to set a unique constraint to the name column and create stored procedures I need it to be done as a conditional described above.
This should work..
$stmt = $conn->prepare(' SELECT (`Active`)
FROM `Table1`
WHERE `Name` = ":name" AND Active <> Yes ');
$stmt->execute([
'name' => $_POST['name']
]);
if ($stmt->rowCount() === 0) {
$stmt = $conn->prepare(' INSERT INTO `Table1` (`Name`,`Active`)
VALUES (:name, :active ) ');
$stmt->execute([
'name' => $_POST['name'],
'active' => $_POST['active']
]);
} else {
$stmt = $conn->prepare('UPDATE `Table1`
SET `active` = `Yes`
WHERE `Name` = `:name`');
$stmt->execute([
'name' => $_POST['name']
]);
}
I have not tried this one out but it should work. Tell me if it doesnt.
Related
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
For some weird reason, my PDO keeps returning NULL when it should return a string/integer. I've tried to use the odbc_conect and it works fine.
Context:
CentOS 7
PHP 7.1.13
unixODBC 2.3.1 (x86_64 . 11.el7)
ODCB Driver: SAP HANA ODBC v2.2.36.1512099132 64 bits
When it's happening? Until now, I detected few:
Function returns: SELECT id,GEO.ST_Asgeojson() FROM DEV.GEOMETRIES
Using CAST: SELECT id, CAST(GEO.ST_AsText() AS VARCHAR) FROM DEV.GEOMETRIES or SELECT CAST(1 AS INTEGER) AS "int" FROM DUMMY
Any blob column : SELECT id,GEO FROM DEV.GEOMETRIES
Date Types: SELECT insertdate FROM DEV.GEOMETRIES
I also tried to use PDOStatement::bindColumn to force data types but was unsuccessful
Where the code :
<?php
try{
ini_set('memory_limit','256M'); //odbc_fetch_array is hungry
// $sql = 'SELECT NOW() AS "now" FROM DUMMY';
$sql = "SELECT id,GEO.ST_Asgeojson(),GEO.ST_AsText(),insertdate FROM DEV.geometries limit 1";
//$sql = "SELECT * FROM DEV.geometries limit 1";
// $sql = "SELECT CAST(GEO.ST_AsText() AS VARCHAR) from geometries";
// $sql = "SELECT CAST(10 AS VARCHAR) from DUMMY";
// $sql = "SELECT CAST(10 AS INTEGER) from DUMMY";
echo "SQL: ",$sql,PHP_EOL;
$DSN = "DRIVER=HANADB;UID=DEV;PWD=DEV#pwd;SERVERNODE=192.168.1.163:39013;DATABASENAME=SYSTEMDB";
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_CASE =>\PDO::CASE_LOWER, //Compatibility with mysql case
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES, true //With or without
];
echo "############# Using PDO:ODBC:",PHP_EOL;
$DB = new \PDO("odbc:".$DSN,'DEV','DEV#pwd',$options);
echo "Driver: ",$DB->getAttribute(\PDO::ATTR_CLIENT_VERSION),PHP_EOL;
echo "Using Prepared Statement:",PHP_EOL;
$stmt = $DB->prepare($sql);
// bindColumn Also doesn't work
//$stmt->bindColumn('id', $id, \PDO::PARAM_INT);
//$stmt->bindColumn('geojson', $geometry, \PDO::PARAM_STR);
$stmt->execute();
/*while ($row = $stmt->fetch(\PDO::FETCH_BOUND)) {
var_dump($row);
var_dump($id, $geometry);
}*/
//var_dump($ret,$stmt);
var_export($stmt->fetchAll());
$stmt->closeCursor();
echo PHP_EOL,"Using Query:",PHP_EOL;
$qR = $DB->query($sql);
foreach($qR as $row){
var_export($row);
}
echo PHP_EOL,PHP_EOL,"############# Using odbc_*( ) Functions",PHP_EOL;
$conn = odbc_connect($DSN,'DEV','DEV#pwd');
$rs = odbc_exec($conn,$sql);
while($row = odbc_fetch_array($rs)){
var_export($row);
}
}catch(\Exception $e){
echo $e->getMessage(),PHP_EOL,$e->getTraceAsString();
}
Output:
############# Using PDO:ODBC:
Using Prepared Statement:
array (
0 =>
array (
'id' => '363491',
'geojson' => NULL,
'geotext' => NULL,
'__dateinsert' => NULL,
'info' => NULL,
),
)
Using Query:
array (
'id' => '363491',
'geojson' => NULL,
'geotext' => NULL,
'insertdate' => NULL,
'info' => NULL,
)
############# Using odbc_*( ) Functions
array (
'id' => '363491',
'geojson' => '{"type": "Point", "coordinates": [16.352878, 48.225628]}',
'geotext' => 'POINT (16.352878 48.225628)',
'insertdate ' => '2018-02-06 15:08:19.414000000',
'info' => NULL,
)
I'm not sure if it's a Drive problem because it works with odbc_* functions, maybe it's a PDO BUG.
In PHP I'm attempting to build a form that needs to check for an ID in one table and if it exists it should create a record in another table. So far, that works but the issue I'm having is when I attempt to handle the case if the ID I checked for didn't exist. If it doesn't exist I'd like to create another one. But every time I try it, I get 500 errors from the server when I fetch the results.
Essentially I made the following function
function trySQL($con, $query, $params) {
$stmt = $con->prepare($query);
$result = $stmt->execute($params);
$id = $stmt->insert_id;
return array($stmt,$result,$id);
}
I call this function multiple times through out my php code but when I call it more then once and attempt to fetch the results it breaks.
$custINSquery = "
INSERT INTO custs (
FirstName,
LastName,
EmailAddress,
PhoneNumber
) VALUES (
:FirstName,
:LastName,
:EmailAddress,
:PhoneNumber
)
";
$createJob = "
INSERT INTO jobs (
custs_id,
StAddress,
State,
ZipCode,
MoistureLocation,
status_id
) VALUES (
:custs_id,
:StAddress,
:State,
:ZipCode,
:IssueDesc,
:status_id
)
";
$custSELquery = "SELECT id, FirstName, LastName, EmailAddress FROM custs WHERE FirstName = :FirstName AND LastName = :LastName AND EmailAddress = :EmailAddress";
$custSELquery_params = array(
':FirstName' => $_POST['FirstName'],
':LastName' => $_POST['LastName'],
':EmailAddress' => $_POST['EmailAddress']
);
$checkcust = trySQL($db, $custSELquery, $custSELquery_params);
$row = $checkcust[0]->fetch();
if(!$row){
$custINSquery_params = array(
':FirstName' => $_POST['FirstName'],
':LastName' => $_POST['LastName'],
':EmailAddress' => $_POST['EmailAddress'],
':PhoneNumber' => $_POST['PhoneNumber']
);
$custins = trySQL($db, $custINSquery, $custINSquery_params);
$custsel = trySQL($db, $custSELquery, $custSELquery_params);
$custs_id = $custsel[0]->fetch();
if ($custs_id != null) {
$createJobParam = array(
':custs_id' => $custs_id,
':StAddress' => $_POST['StAddress'],
':State' => $_POST['State'],
':ZipCode' => $_POST['ZipCode'],
':IssueDesc' => $_POST['MoistureLocation'],
':status_id' => $_POST['status_id']
);
$jobins = trySQL($db, $createJob, $createJobParam);
$jobres = $jobins[0]->fetch();
die("um...");
if ($jobres) {
# code...
die("looks like I made it");
}
}
} else {
$createJobParam = array(
':custs_id' => $row['id'],
':StAddress' => $_POST['StAddress'],
':State' => $_POST['State'],
':ZipCode' => $_POST['ZipCode'],
':IssueDesc' => $_POST['MoistureLocation'],
':status_id' => $_POST['status_id']
);
$data['success'] = true;
$data['message'] = 'Success!';
}
Additional Notes: When I look through the php doc's they are saying that I could use the inserted_id thing in order to get the ID that I inserted previously but when I try that it just gives me nulls with this set up.
Any help would be appreciated.
Thanks!
I have a little problem. I'm very new to mysql and I'm creating some sort of basic database of cats. I'm adding 100 positions to database through that code:
$result_set = $pdo->prepare("INSERT INTO koty2 (name, age, breed, author, tag, image) VALUES (:name, :age, :breed, :author, :tag, :image)");
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
for ($i=0; $i<100; $i++) {
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
I tried multiple ways of adding the $name to the database with row's ID which is auto incremented - so it would be "Name+ID". So far I failed. Can somebody tell me how to do this?
Thank you.
One work around is, you can first insert the data you want to insert, get the last inserted ID, then just update the name by concatenating the name and ID. See below code:
// insert first
$result_set = $pdo->prepare("INSERT INTO koty2 (name, age, breed, author, tag, image) VALUES (:name, :age, :breed, :author, :tag, :image)");
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
// get the inserted ID
$last_ins_id = $pdo->lastInsertId();
// update the inserted name
$update_row = $pdo->prepare("UPDATE koty2 SET name = :name WHERE ID = :id");
$update_row->execute(array(
':name' => $name . $last_ins_id,
':id' => $last_ins_id
));
Im not sure if this is the best solution but this logic will still do the work
If you want to get the inserted auto-incremented ID everytime you insert a new Cat( xD ), you can use:
$pdo->lastInsertId();
http://php.net/manual/en/pdo.lastinsertid.php
This will echo the whole column "$Name $CatID" do what you want:
$stmt = $pdo->query("SELECT name, catID FROM koty2");
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
print "Name: <p>{$row[0] $row[1]}</p>";
}
For more, check:
http://php.net/manual/en/pdostatement.fetch.php
This is my query:
SELECT * FROM mytable WHERE `USER` = '1599' AND `id` = '124253' AND `wednesday` IS NULL
This is the php code:
$check = Test::model()->find("id =:id and user =:user and ".$day." =:day ", array(":id" => $check_lunch_per_day, ":user" => $user, 'day'=> null));
another try:
$check = Test::model()->find("id =:id and user =:user and ".$day." =:day ", array(":id" => $check_lunch_per_day, ":user" => $user, 'day'=> 'IS NULL'));
But the result of the check is always null. What should I do? I want to get the wednesday column value if it is null.
This should work,
setting :day to IS NULL
$check = Test::model()->find("id =:id and user =:user and ".$day." =:day ",
array(":id" => $check_lunch_per_day, ":user" => $user, ':day'=> 'IS NULL'));