safemysql
safemysql copied to clipboard
Show how to INSERT?
Can you please add a full CRUD example.
And why not make it use PDO instead?
wrong example deleted
@AlexMerser21 this is utterly wrong example.
The point of the library is to use a placeholder for the every dynamical value. While keys
and values
are obviously supposed to be dynamic. So, for the insert query you have 2 options:
Either run INSERT query the same way as other queries:
$sql = "INSERT INTO ?n values (NULL, ?s, ?s, ?s, null, UNIX_TIMESTAMP(), ?i, ?s, ?s)";
$db->query($sql, $table, $_POST['name'], $_SERVER['REMOTE_ADDR'],
$_POST['body'], $del, $h, $_POST['topic']);
Or create an array with key-value pairs for all the variable values, and then use ?u placeholder:
$sql = "INSERT INTO ?n SET ts = UNIX_TIMESTAMP(), ?u";
$data = array(
'name' => $_POST['name'],
'ip' => $_SERVER['REMOTE_ADDR'],
'body' => $_POST['body'],
'del' => $del,
'topic' => $_POST['topic'],
);
$db->query($sql, $table, $data);
@colshrapnel но чем плохо такое использование? Я в пхп недавно и всегда писал свои приложение именно вот так. Пожалуйста распишите, если не сложно
Да и в CRUD приложение написано так-же http://phpfaq.ru/crud
In your example some variables were going into query as is - without any formatting.
@colshrapnel How to get last inserted id in this case?
@laughtingman
just use the insertId()
method. I.e.
$sql = "INSERT INTO ....)";
$db->query($sql, $value);
$id = $db->insertId();
When using ?u with an array containing false value, the value becomes empty string on insert.
e.g.
$post = [];
$post['myvalue'] = false;
$db->query('INSERT INTO ?n SET ?u', $table, $post);
PHP Fatal error: SafeMySQL: Incorrect integer value: '' for column myvalue at row 1. Full query: [INSERT INTO mytable SET myvalue='', ...
The field myvalue is tinyint(1) DEFAULT NULL (BOOLEAN)
@Perlovka indeed ?u doesn't work with STRICT MODE. To solve the problem just send it as int:
$myvalue = false;
$db->query('INSERT INTO ?n SET myvalue =?i', $table, (int)$myvalue);
You can still insert other values using ?u:
$post = ['foo' => 1, 'bar' => 2];
$myvalue = 0;
$db->query('INSERT INTO ?n SET myvalue =?i, ?u', $table, $myvalue, $post);
In case this field have to be added dynamically, then you have to resort to ?p method
if (some condition) {
$add = $db->parse("myvalue = ?i,", $myvalue);
}
$db->query('INSERT INTO ?n SET ?p ?u', $table, $add, $post);
This is the most inconvenient method but it's all safemysql can do in this case.
Thanks, i just wondered if it's so by design, int is ok for me )