...
Code Block | ||||
---|---|---|---|---|
| ||||
// string prepare(string $statement, array $values) $values = array( 'table_art_lang' => $cfg['tab']['art_lang'], 'idart' => (int) $idart, 'idlang' => (int) $idlang ); $sql = $db->prepare('SELECT * FROM `:table_art_lang` WHERE idart = :idart AND idlang = :idlang', $values); $db->query($sql); |
insert()
The new method insert() can be used to create a new record in a given database table. It is an alternative to the manual creation of an INSERT statement.
The manual creation of an INSERT statement usually looks something like this:
Code Block | ||||
---|---|---|---|---|
| ||||
$idcode = 123;
$idcatart = 12;
$idlang = 1;
$idclient = 1;
$code = "<html>... code n' fun ...</html>";
$cfg = cRegistry::getConfig();
$db = cRegistry::getDb();
$sql = "INSERT INTO ".$cfg["tab"]["code"]." (idcode, idcatart, code, idlang, idclient)
VALUES (".cSecurity::toInteger($idcode).", ".cSecurity::toInteger($idcatart).",
'".cSecurity::escapeDB($code, $db)."', ".cSecurity::toInteger($idlang).",
".cSecurity::toInteger($idclient).")";
$db->query($sql); |
The method insert() is an alternative. The first parameter is the database table name whereas the second parameter is an associative array with array keys as column names and array values as record values.
Code Block | ||||
---|---|---|---|---|
| ||||
// bool insert(string $tablename, array $fields)
$idcatart = 12;
$idlang = 1;
$idclient = 1;
$code = "<html>... code n' fun ...</html>";
$fields = array(
'idcatart' => (int) $idcatart,
'idlang' => (int) $idlang,
'idclient' => (int) $idclient,
'code' => $code,
);
$cfg = cRegistry::getConfig();
$db = cRegistry::getDb();
$result = $db->insert($cfg['tab']['code'], $fields); |
Integer values should be casted whereas strings will be escaped automatically.
The observant reader might have noticed that no idcode was defined. From CONTENIDO 4.9 on the sequence table for managing IDs was removed. It's no more neccessary to retrieve the next ID via $db->nextid() as ID columns are now defined as AUTOINCREMENT and MySQL is responsible for the determination of IDs.
buildInsert()
While insert() creates an INSERT statement and executes it immediatly, buildInsert() will just create and return the statement. This is usefull if the statement should be used otherwise (e.g. logged) before being executed.
Code Block | ||||
---|---|---|---|---|
| ||||
// string buildInsert(string $tablename, array $fields)
$idcatart = 12;
$idlang = 1;
$idclient = 1;
$code = "<html>... code n' fun ...</html>";
$fields = array(
'idcatart' => (int) $idcatart,
'idlang' => (int) $idlang,
'idclient' => (int) $idclient,
'code' => $code,
);
$cfg = cRegistry::getConfig();
$db = cRegistry::getDb();
$sql = $db->buildInsert($cfg['tab']['code'], $fields);
$result = $db->query($sql); |