Phalcon PHP: Update a primary natural key - php

Is there a good way to be able to update a table which has a natural key in Phalcon?
Consider this table:
people
------
person
created_at
updated_at
We're going to assume that the person field is unique and is the primary key. I try to do the following:
$person = new People();
$person->person = 'Ed';
$person->save();
$personUpdate = People::findFirst('person = "Ed"');
$personUpdate->person = 'Bob';
$person->save();
What Phalcon ends up trying to do is to INSERT a new record, rather than to update the existing record. What I need it to do is to UPDATE ... WHERE person = 'Ed';
Thoughts?
Thanks!

Try the following...
<?php
$personUpdate = People::findFirst('person = "Ed"');
$personUpdate->person = 'Bob';
$person->update();

You are doing correct except ... People::find
find will prepare to fetch all data.. this means its in array Documentation
You need to use findFirst instead of find
$personUpdate = People::findFirst('person = "Ed"');
$personUpdate->person = 'Bob';
$person->save();

Please note that you are using $person->update() instea of $personUpdate->update();
<?php
$personUpdate = People::findFirst('person = "Ed"');
$personUpdate->person = 'Bob';
$person->update();

Related

mySQL: UPDATE statement for 2 tables with a foreign key relation

I have created 2 tables with the following structure:
mitarbeiter
==================
maID (PK, AUTO_INCREMENT, NOT NULL)
maAnrede
maName
maVname
maDurchwahl
maEmail
maMobilfunkNr
maKartenanzahl
maFirma
mobilfunkkarten
==============================
mfkID (PK, AUTO_INCREMENT, NOT NULL)
mfkTarif
mfkStatus
mfkKartennr
mfkPin
mfkSuperpin
maID(FK)
Now I would like the web user to type in values into form fields. (I will let him edit his/her entries there, which will be saved in the mysql-database. So these entries are NOT new!) After clicking the "Save"-Button, the data will be saved into the corresponding 2 tables. My mySQL-Query looks like this (I am using symfony's php templating engine "twig"):
DatabaseLink::getInstance()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["btnSaveMfk"]))
{
$stmt = DatabaseLink::getInstance()->prepare("UPDATE mitarbeiter SET
maAnrede = :maAnrede,
maVname = :maVname,
maName = :maName,
maMobilfunkNr = :maMobilfunkNr,
maKartenanzahl = :maKartenanzahl,
maEmail = :maEmail,
maFirma = :maFirma
WHERE mitarbeiter.maID = :maid;
UPDATE mobilfunkkarten SET mfkTarif = :mfkTarif,
mfkStatus = :mfkStatus,
mfkPin = :mfkPin,
mfkSuperpin = :mfkSuperpin");
$status = $stmt->execute(array(
":maid" => $_POST["txtMaId"],
":maAnrede" => $_POST["txtAnrede"],
..................,
..................,
..................
));
header("Location: Mobilfunkdaten"); //back to the PHP table that shows all entries
}
I believe that this won't work because the 2 tables are related with a foreign key and if I update both tables without this relation, the statement will result in an error or it will overwrite something unrelated. Am I right with this assumption?
Any solutions on how to solve this? I just can't think of any way on how to make sure that anything the user types into the form fields will be saved as 1 dataset into these 2 tables, i.e. the UPDATED data in the child table 'mobilfunkkarten' will be related to the Primary Key Number in the parent table 'mitarbeiter'.
mitarbeiter = workers mobilfunkkarten = mobile phone cards (SIM cards)
With update statements, the auto_increment value doesn't change. And, as I can see from your query, you're not updating the maID value, so it gives no reason for the MySQL parser to throw an error. Your query is correct, as far as I can see.
Just one small thing. Define the keys of the associative array without the : symbol. You use this symbol to indicate that this place is reserved for the value stored in the variable by the following name. For example, using
$stmt = DatabaseLink::getInstance()->prepare("update table_name set name=:name where id=:id");
$status = $stmt->execute(array("name" => "test", "id" => 2));
indicates to the parser that the name corresponding to ID 2 has to be updated to test.
But, you are already using the : along with the name of the key. So, in your example, your query looks for the value in a key called maAnrede in your script, but the key that you have defined is :maAnrede, and hence, the query doesn't work as expected.
Try this change. It'll surely work.
DatabaseLink::getInstance()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["btnSaveMfk"]))
{
$stmt = DatabaseLink::getInstance()->prepare("UPDATE mitarbeiter SET
maAnrede = :maAnrede,
maVname = :maVname,
maName = :maName,
maMobilfunkNr = :maMobilfunkNr,
maKartenanzahl = :maKartenanzahl,
maEmail = :maEmail,
maFirma = :maFirma
WHERE mitarbeiter.maID = :maid;
UPDATE mobilfunkkarten SET mfkTarif = :mfkTarif,
mfkStatus = :mfkStatus,
mfkPin = :mfkPin,
mfkSuperpin = :mfkSuperpin");
$status = $stmt->execute(array(
"maid" => $_POST["txtMaId"],
"maAnrede" => $_POST["txtAnrede"],
..................,
..................,
..................
));
header("Location: Mobilfunkdaten"); //back to the PHP table that shows all entries
}
This situation happened with me as well, and this is the solution that worked for me!
I believe I fixed it. You need to add this line in the second SQL statement:
WHERE mobilfunkkarten.maID = :maid");
See below where I included it.
Fixed the issue for me but I am not entirely sure how safe this one is...any criticism on this approach? Other suggestions?
DatabaseLink::getInstance()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["btnSaveMfk"]))
{
$stmt = DatabaseLink::getInstance()->prepare("UPDATE mitarbeiter SET
maAnrede = :maAnrede,
maVname = :maVname,
maName = :maName,
maMobilfunkNr = :maMobilfunkNr,
maKartenanzahl = :maKartenanzahl,
maEmail = :maEmail,
maFirma = :maFirma
WHERE mitarbeiter.maID = :maid;
UPDATE mobilfunkkarten SET mfkTarif = :mfkTarif,
mfkStatus = :mfkStatus,
mfkPin = :mfkPin,
mfkSuperpin = :mfkSuperpin
WHERE mobilfunkkarten.maID = :maid");
$status = $stmt->execute(array(
"maid" => $_POST["txtMaId"],
"maAnrede" => $_POST["txtAnrede"],
..................,
..................,
..................
));
header("Location: Mobilfunkdaten"); //back to the PHP table that shows all entries
}

Laravel - php How to get current Id while inserting value in Database?

I want to get the current ID while inserting the value in database.Which i will use to save custom Data. How Do I do it?
I have written a query already.
$currentId = Student::orderBy('id', 'desc')->get(['id']) + 1;
But it's showing the following Error :
Object of class Illuminate\Database\Eloquent\Collection could not be
converted to int
$currentId = Student::orderBy('id', 'desc')->first()->id + 1;
But on the heavy traffic website this potentially can cause problems with data integrity, so I'd user this approach:
$student = new Student();
....
$student->save();
$currentId = $student->id;
try this
$data = Student::orderBy('id', 'desc')->get(['id']);
$data->getId();
You have to do something like this :-
$insertData['name'] = 'your name';
$insertData['password'] = 'password';
..
etc..
// $insertData this will be your array which you want to insert in your db. name and password used in insertData array will be same as your table column name..
$lastId = Student::insertGetId($insertData);
It will give you last inserted id in laravel, it will help you.

how to read yii create command object without foreachloop

I use create command of Yii as
$sql = "select name from users where id = 2";
$EmployeeName=Yii::app()->db->createCommand($sql)->queryAll();
now i have to use foreachloop to get specific value like
foreach($EmployeeName as $value)
$name = $value['name'];
Can i bypass foreach loop like
$EmployeeName -> name; //To get value of specific field
Question is why i use foreach loop when i know i have single index array?
when i am using print_r($EmployeeName) its showing me sql command in object instead of data so i am confused how to debug object array
Assuming id is your primary key, you should use queryScalar instead. This will return a single value and not an array.
$name=Yii::app()->db->createCommand($sql)->queryScalar();
You can use this syntax in Yii:
$user = Users::model()->findByAttributes(array('id' => 2));
$name = $user->name;
echo $name;
Single line solution
The simplest approach is find by primary key (PK).
Suppose id is PK in the Users model (Users model should be set thru gii model generator):
$name = Users::model()->findByPk(2)->name;

How to get all column names of a row in cassandra using phpcassa?

I want to get all column names of a row in cassandra , how can I do it in phpcassa?
If phpcassa does not support it, does any other language, libs can do it?
In my case, column names are short, but rows are long(around 1000+),data are big(around 100K)
You have a good question. Try something like that:
$pool = new ConnectionPool('feed', array('127.0.0.1'));
$raw = $pool->get();
$rows = $raw->client->execute_cql_query("SELECT * FROM posts", cassandra_Compression::NONE);
var_dump($rows);
Maybe it will help...
Do you mean to get the names directly and only with phpCassa? I don't know any way to do it directly but I used to do that by getting all the row and then executing a foreach loop over the array I have from the column family, like this:
1.- A small function to use everywhere (build your own if you need ;) ):
function f_get_data_as_array($p_pool, $p_cf, $p_key, $p_col_count = 100, $p_column_names = NULL, $p_range_start = '', $p_range_end = '', $p_inverted_sort = false)
{
try{
$lv_slice = new ColumnSlice($p_range_start, $p_range_end, $p_col_count, p_inverted_sort);
$lv_cf = new ColumnFamily($p_pool, $p_cf);
$lv_cf->insert_format = ColumnFamily::ARRAY_FORMAT;
$lv_cf->return_format = ColumnFamily::ARRAY_FORMAT;
$lv_result = $lv_cf->get($p_key, $lv_slice, $p_column_names);
}catch(Exception $lv_e)
{
return false;
}
return $lv_result;
2.- I call it using the first four parameters, setting the pool, the column family name, the key I need and the number of columns I want to get (set the number as you need).
3.- A foreach loop over the returned array to get each column name. Or, if you know the structure you will get from your column family, you just need to use the right indexes, probably: $lv_result[0][0], $lv_result[0][1], and so...
Hope it helps. And sorry for my English!

Mysql_insert_id with Doctrine

I have a couple of tables (mySQL) that i would like to update with the help of Doctrine. The products table id is auto-incrementing, and here's a brief description on what I would like to do:
$prod = new Products();
$prod->type = '0';
$categ = new CategoriesToProducts();
$categ->cat = '111';
$categ->product = $prod->id;
$conn = Doctrine_Manager::connection();
$conn->flush();
How can I do this while using flush? Using a regular save is an alternative, but there will be multiple transactions while doing such.
I have tried to find a Mysql_insert_id version for doctrine, but without any luck.
Thanks!
Here you can find some information: http://www.doctrine-project.org/documentation/manual/2_0/en/basic-mapping#identifiers-/-primary-keys

Categories