PDO Postgres - Check if Column Exist and do action based off condition - php

I'm trying to check to see if a column exists.. If it does, then I want to update the value, and if it doesn't, I want to alter the table and add the column with the a value. I'm pretty new to PDO, but I'm pretty sure my query is fine, I just don't know how to handle the output from the execute() command I guess. Thanks for the help in advance!
$sth = $pdo->prepare(' SELECT ? FROM `?` WHERE column_name=? ');
$sth->bindParam(1, $column, PDO::PARAM_STR);
$sth->bindParam(2, $livetable, PDO::PARAM_STR);
$sth->bindParam(3, $column, PDO::PARAM_STR);
$sth->execute();
if ($sth) {
//Row Exist - Update Value
echo 'Row Exist';
}else{
//Row Doesn't Exist - Create column & update with value
echo 'row does not';
}

You cannot pass a table name as a bind parameter like this, you would need to use dynamic SQL to achieve this. But if you just want to check if a column exist in a table, don’t query the table directly (what if it contains millions of records ?) ; instead, query Postgres information schema, as follows :
SELECT column_name
FROM information_schema.columns
WHERE
table_name = ?
AND column_name = ?;

Related

Foreach in foreach check data?

I have an xml file where I get the data. I record this data in the database and make updates. Now I am faced with a situation whose logic I cannot solve.
I want to do; I want to check the data in the database for the data I get from XML, to add if there is any unattached data and to update it if it is added.
Sample codes are as follows. Thank you in advance for your support
$current = simplexml_load_file('http://example.com/simple.xml');
foreach($current->simple as $item){
// Database Control data
$tax = $item->tax;
$data = $db->query("SELECT*FROM current WHERE tax_number = '$tax' ");
foreach($data->results() as $row){
if(isset($data))
{
// Edit
}
else
{
// Insert
}
}
}
According to the codes above, there is a situation like this. For example, if there are 50 data in the XML file, it returns 50 * 500 times if there is 500 data in the current table, multiplying each data by the number in the table I want to control. And he just adds.
Considering you'll have unique value per tax_number in your table. You should make this tax_number column as unique.
ALTER TABLE `current`
ADD UNIQUE INDEX `tax_number` (`tax_number`);
Once done you can use mysql INSERT ... ON DUPLICATE KEY UPDATE feature to insert a record or update existing record in single query for a given tax_number.
Considering you have col1, col2 and tax_number as columns in your table and you want to update col1 if this record already exists. So mysql query would be
INSERT INTO `current` (col1, col2, tax_number)
VALUES ('a', 'b', 12345)
ON DUPLICATE KEY UPDATE col1 = 'a';
Note: Your code is vulnerable to sql injection, make sure you update your code by PDO with parameter binding.
So corresponding code in php would be like this.
$current = simplexml_load_file('http://example.com/simple.xml');
foreach($current->simple as $item){
$query = $db->prepare('INSERT INTO current (currentDocumentNumber, currentTaxNumber, currentIdentity,currentOperationType,currentAmountOfDebt,currentAmountDue,currentAccountDate)
VALUES (:doc_number, :tax_number, :identity, :operation_type, :debt_amount, :due_amount, :date)
ON DUPLICATE KEY UPDATE currentAmountOfDebt = :debt_amount, currentAmountDue = :due_amount');
$query->bindParam(':doc_number', $item->EVRAK_NO, PDO::PARAM_STR);
$query->bindParam(':tax_number', $item->VERGI_NO, PDO::PARAM_INT);
$query->bindParam(':identity', $item->TC_KIMLIK_NO, PDO::PARAM_STR);
$query->bindParam(':operation_type', $item->ISLEM_TURU, PDO::PARAM_INT);
$query->bindParam(':debt_amount', $item->KPB_BTUT, PDO::PARAM_STR);
$query->bindParam(':due_amount', $item->KPB_ATUT, PDO::PARAM_STR);
$query->bindParam(':date', $item->TARIHI, PDO::PARAM_STR);
$query->execute();
}

PDO update query to append data into MYSQL db using named placeholder

I'm building sql UPDATE query to append string value using only NAMED PLACEHOLDERS to the already existing value in db. please suggest necessary changes in below code to work or suggest how to use named placedholders in concat update syntax
$name="Lastname";
$stmt = $conn->prepare("UPDATE users SET name= name + :name WHERE id=:id");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':id', $id);
$stmt->execute();
Expected Output:
Before: Table has 'name' column-value "Firstname"
After code execution: 'name' column-value "FirstnameLastname"
+ is not the normal way to concatenate strings in SQL. The standard operator is || and the function concat() is usually available:
UPDATE users
SET name = CONCAT(name, :name)
WHERE id = :id;

Update a single row in SQL

I am having trouble with a really simple SQL statement: UPDATE.
I would only like to update the booking_date column in a specific row.
Here is the statement I'm using:
UPDATE `coupon-codes` SET `booking_id`=:timestamp WHERE `id` = :id
I'm using PDO named placeholders.
I always get an incorrect syntax error. What am I doing wrong?
Edit:
I tried without backticks:
UPDATE coupon-codes SET booking_id = :timestamp WHERE id = :id
Still doesn't work.
Here's the error message I'm getting:
Edit 2:
Here is the error message I'm getting when using backticks:
Edit 3:
For reference, here is an INSERT statement I used before, which works without any problems:
INSERT INTO `coupon-codes` (`code`, `date`) VALUES (:code, :date)
Edit 4:
Sorry, wrongly said some things in the comments, to clarify, see this:
I am using BACKTICKS everywhere. This is the query that doesnt work:
UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id
I also had a typo in the original question which had booking_id instead of booking_date field, but that doesn't matter, since I'm getting a SYNTAX ERROR.
Here is the PHP code I'm trying to run it with:
$stmt = $db->prepare("UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id");
$stmt->bindParam(':timestamp', $time);
$stmt->bindParam(':id', $id);
$stmt->execute();
Basic MySQL syntax:
'foo' - single-quotes. turns the quote word into a string literal
`foo` - backticks. used to escape table/fieldnames that happen to be reserved words
SELECT 'select' FROM ... -- select the literal word "select" from some table
SELECT `select` FROM ... -- select the field NAMED "select" from some table
SELECT select FROM ... -- syntax error - using a reserved word "select"
Given your error messages, you probably have one of the following:
UPDATE 'coupon-code' ... -- can't update a string. must specify a table name
UPDATE coupon-code ... -- math operation: coupon MINUS code - not a table name
Have you tried to use Predefined Constants (http://php.net/manual/en/pdo.constants.php);
Example:
$stmt = $db->prepare("UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id");
$stmt->bindParam(':timestamp', $time, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

PDO insert new record to database based on lastInsertId()

Ive just started learning PDO and I'm struggling by simply inserting a new record based from
$lastid = $db->lastInsertId();
The ID gets created in the database table from another function.
But nothing happens when i try to insert a new record based on that ID.
function add_name($last_id, $name) {
$db = some_db();
$query = "INSERT INTO team (name) VALUES (:name) WHERE id = '".$last_id."'";
$stmt = $db->prepare($query);
$stmt ->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
}
INSERT ... WHERE is not valid SQL. If you are inserting a new record, an autoincremnt ID will be generated at that time (if you have such defined for the table).
If you are trying to INSERT a new row into a related table with the last id from another table, then you would set that value as one of your column inputs. So the workflow would look like this:
INSERT [column data for table_a] INTO table_a
[GET autoincrement from last insert]
INSERT (table_a_foreign_key_column, [other table_b columns]) VALUES (table_a_id, [other table_b values) INTO table_b
UPDATE:
Since UPDATE is what you want, you can make update like this:
UPDATE team
SET name = :name
WHERE id = :id
You should use parameters for both name and id values. It is still not clear to me why you would need to make an insert and then an update within the same script execution. It's not like you received any more input from the user that you did not already have. I would guess you could just insert this name values when first creating the record and save yourself the extra trouble of multiple queries.
i think your sql query is wrong, try this:
function add_name($last_id, $name) {
$db = some_db();
$query = 'INSERT INTO team (id, name) VALUES (:id, :name)';
$stmt = $db->prepare($query);
$stmt ->bindParam(':name', $name, PDO::PARAM_STR);
$stmt ->bindParam(':id', $last_id, PDO::PARAM_INT);
$stmt->execute();
}
MySQL Insert Where query

dynamic update query using bind params

I am into situation where i dont know which fields would be set to update , i can get the columns and respected values which need to updated, but how can i get the type of each field for binding parameters using mysqli ?
UPDATE City SET Name = ?,CountryCode = ?,District = ? WHERE 1
Lets say this is the query i got as for now .. and I would something like this to update ..
$stmt = $conn->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('sss', $name, $countrycode, $district);
$stmt->execute();
}
but what if i dont know 'sss' ( in dynamic context ) ?
You can use string for everything. MySQL will convert strings to numbers when necessary. Just as you can do something like:
SET id = '123'
when writing a regular query.

Categories