Im tying to update a table with the followning function in PHP. The problem is that the second parameter $work_place is not accepted and the update fails. This is my first time working with PHP and mySQL so my knowledge is a bit limited.
public function timestampOut($work_done, $work_place)
{
// clean the input to prevent for example javascript within the notes.
$work_done = strip_tags($work_done);
$work_place = strip_tags($work_place);
$userLastTimestampID = $this->getUserLastTimestampID();
$sql = "UPDATE timestamps SET timestamp_work_description = :work_done, timestamp_work_dropdown = :work_place, timestamp_out = now() WHERE timestamp_id = $userLastTimestampID[0] AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->execute(array(':work_done' => $work_done, ':user_id' => $_SESSION['user_id']));
$count = $query->rowCount();
if ($count == 1) {
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
You just need to add work_place to the param array in your execute call, like so:
$query->execute(array(':work_done' => $work_done, ':work_place' => $work_place, ':user_id' => $_SESSION['user_id']));
Please read again how execute works. You would want to use it like this:
$query->execute(array(':work_done' => $work_done, ':work_place' => $work_place, ':user_id' => $_SESSION['user_id']));
Try to replace
$query->execute(array(':work_done' => $work_done, ':user_id' => $_SESSION['user_id']));
with
$query->execute(array(':work_done' => $work_done, ':user_id' => $_SESSION['user_id']), ':work_place' => $work_place);
Related
This is my code:
if (preg_match('/^\/start (.*)/', $text, $match) or preg_match('/^\/get_(.*)/', $text, $match)) {
$id = $match[1];
if (isJoin($from_id)) {
$fileData = mysqli_query($db, "SELECT * FROM `file` WHERE `id` = '{$id}'");
$file = mysqli_fetch_assoc($fileData);
if (mysqli_num_rows($fileData)) {
if ($file['password']) {
sendMessage($from_id, "please send pass :", "markdown", $btn_back, $message_id);
mysqli_query($db, "UPDATE `user` SET `step` = 'password', `getFile` = '$id' WHERE `from_id` = '$from_id'");
} else {
$downloads = number_format($file['downloads']);
$downloads++;
$caption = urldecode($file['caption']);
Ilyad("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file['file_id'],
'caption' => "š„ count : <code>{$downloads}</code>\n{$caption}\n Thanks",
'parse_mode' => "html",
]);
Ilyad("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file['file_id2'],
'caption' => "š„ count : <code>{$downloads}</code>\n{$caption}\n Thanks",
'parse_mode' => "html",
]);
mysqli_query($db, "UPDATE `file` SET `downloads` = `downloads`+1 WHERE `id` = '$id'");
mysqli_query($db, "UPDATE `user` SET `step` = 'none', `downloads` = `downloads`+1 WHERE `from_id` = '$from_id'");
}
} else sendMessage($from_id, "hi welcome to bot", 'markdown', $btn_home, $message_id);
} else {
joinSend($from_id);
mysqli_query($db, "UPDATE `user` SET `getFile` = '$id' WHERE `from_id` = '$from_id'");
}
}
so what i want to do is repeat this code like 24 times but each time the number at the end of file_id changes like file_id1, file_id2, file_id3, ..., file_id24.
and the values for file_id1, ... and others are stored on my SQL database.
Now if you see there is two codes repeating and the only change is the number at the end of file_id so i want to make it 24 codes but instead of just repeating it I want to do it with one code.
and another thing I said 1 to 24 can i also do something so it reads the last number from a database value to like loop from 1 to x and x is the number i entered in database.
sorry i'm new to programming.
All you need to do is wrap that code in a for loop that increments 1..N. Then in the body of the loop, append / interpolate the loop increment variable where you need it.
for ($i = 1; $i <= 24; $i++) {
// ...
("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file["file_id$i"],
'caption' => "š„ Count : <code>{$downloads}</code>\n{$caption}\nš” Thanks",
'parse_mode' => "html",
]);
}
I've just begun developing code in php, and currently I'm developing a small API for a faculty at my university.
I'm using prepared statements to interact with a MySQL database, but in this function the parameters do not get passed to the function.
function patch_admin() {
global $db,$file, $settings;
$payload = get_json();
if($payload[password_crypt] != NULL)
{
metamessage(lang('please_use_password_function'));
return HTTP_BAD_REQUEST;
}
if($payload[admin_id] != NULL)
{
foreach($payload as $key => $value) {
if($key == "admin_id") { continue; }
$querystr="UPDATE " .table('admin'). " SET :key=:value WHERE admin_id=:admin_id";
$params = [ ':key' => $key, ':value' => $value, ':admin_id' => $payload[admin_id]];
$query = $db->prepare($querystr);
$query->execute($params);
}
}
return HTTP_BAD_REQUEST;
}
The query and the parameters look like this:
UPDATE or_admin
SET :key = :value
WHERE admin_id=:admin_id
Array
(
[:key] => fname
[:value] => Bernharddiener
[:admin_id] => 1626704194
)
Am I missing something obvious here?
When I replace the :key with the field names, I'm able to patch the database, but I want to get the column names from the JSON I send.
Best regards,
Til
You should check and set params the same way you do with the table name
Ex :
$querystr="UPDATE " .table('admin'). " SET `".mysql_real_escape_string($key)."` =:value WHERE admin_id=:admin_id";
$params = [ ':value' => $value, ':admin_id' => $payload[admin_id]];
Is there a way with MySQL to specify "use previous / inherit / no change / existing value"?
Rather than needing to pull the current data from the database and use it, or have a customized database function excluding editing those columns.
if(x > y) {
$role_id = 3;
} else {
$role_id = '#no-change'; // Is there a way to do this? (not proper SQL syntax)
}
$update_user = $this->db->update('users',
array(
'first_name' => filterName($post['first_name']),
'last_name' => filterName($post['last_name']),
'email' => filterEmail($post['email']),
'role_id' => $role_id,
), $user_id_to_edit, 'user_id');
In a case like this where the db function is using prepared statements (not shown) I can't use the column name as to reflect the current value.
Is there such a MySQL function / variable that will essentially "ignore" updating that column? (just leave the existing value)
UPDATE: Here's the Update function:
public function update($table, $data, $where_id, $column = 'user_id') {
// Check for $table or $data not set
if (( empty( $table ) || empty( $data )) || empty($data) ) {
return false;
}
// Initiate variable to append to
$placeholders ='';
// Parse data for column and placeholder names
foreach ($data as $key => $value) {
$placeholders .= sprintf('%s=:%s,', $key, $key);
}
// Trim excess commas
$placeholders = rtrim($placeholders, ',');
// Append where ID to $data
$data['where_id'] = $where_id;
// Prepary our query for binding
$stmt = $this->db->prepare("UPDATE {$table} SET {$placeholders} WHERE $column = :where_id");
// Execute the query
$stmt->execute($data);
// Check for successful insertion
if ( $stmt->rowCount() ) {
return true;
}
return false;
}
You could try this:
$data = array(
'first_name' => filterName($post['first_name']),
'last_name' => filterName($post['last_name']),
'email' => filterEmail($post['email']))
if(x > y) {
$data['role_id'] = 3;
}
$update_user = $this->db->update('users', $data, $user_id_to_edit, 'user_id');
That way, you can customize $data before hand if you like.
I should also mention, if you're concerned about redundancy, you can put your data sanitation inside a function. Something along the lines of:
function sanitize($data) {
if(x > y) {
$data['role_id'] = 3;
} else {
if(isset($data['role_id']) {
unset($data['role_id']);
}
}
return $data;
}
$data = array(
'first_name' => filterName($post['first_name']),
'last_name' => filterName($post['last_name']),
'email' => filterEmail($post['email']))
$update_user = $this->db->update('users', sanitize($data), $user_id_to_edit, 'user_id');
Edit: Something I should mention is that, if we're talking pure SQL, all you need to do is omit those columns from the query, so:
UPDATE table SET Col1=val1, Col2=val2, Col3=val3 WHERE id=val
But if for some reason you don't want to update Col3, just remove it from the query:
UPDATE table SET Col1=val1, Col2=val2 WHERE id=val
Since you have a function that just adds whatever you give it, you just need to sanitize the data ahead of time. That's probably the best way to do it.
I need to create a drcode using the last insert id in the prescribed format,
previously I have used cor php to get the code but now in codeigniter am not able to get the code as the previous one. How can i do this? I am providing my controller and model
Controller
public function newdoctor_post() {
$employee_id = $this->post('EMPLOYEE_ID');
$doctorname = $this->post('DOCTOR_NAME');
$mobilenumber = $this->post('DRMOBILE');
$users_data = $this->Rest_user_model->doctor_exists($mobilenumber);
if ($users_data == 1) {
$message = ['status' => 2,
// 'result' => array(),
'message' => 'Doctor already registered'];
} else {
$speciality = $this->post('SPECIALITY');
$longitude = $this->post('LONGITUDE');
$latitude = $this->post('LATITUDE');
$drcode = $this->post('DRCODE');
$createdon = date('Y-m-d H:i:s');
$insert_array = array('EMPLOYEE_ID' => $employee_id, 'DOCTOR_NAME' => $doctorname, 'DRMOBILE' => $mobilenumber, 'SPECIALITY' => $speciality, 'LONGITUDE' => $longitude, 'LATITUDE' => $latitude, 'CREATEDON' => $createdon);
$users_data = $this->Rest_user_model->doctorregistration($insert_array);
$message = ['status' => 1, // 'result' => $users_data,
'message' => 'Doctor Registered Successfully'];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
Model
public function doctorregistration($data) {
if (!empty($data)) {
$this->db->insert('DOCTORDETAILS', $data);
return $this->db->insert_id();
}
return 0;
}
Code Generation
$sql1="SELECT DRCODE FROM DOCTORDETAILS ORDER BY DRCODEDESC LIMIT 1";
$query=mysql_query($sql1);
if (!$sql1) { // add this check.
die('Invalid query: ' . mysql_error());
}
$output_array2=array();
while($row=mysql_fetch_assoc($query))
{
$ids=$row['DRCODE'];
}
// echo $ids;
if($ids){
$su=1;
$num =$num = 'DR' . str_pad($su + substr($ids, 3), 6, '0', STR_PAD_LEFT);;
$unique=$num;
}else{
$unique='DR000001';
}
Try this - replace this code below with your Code Generation code.
$sql1="SELECT DRCODE FROM DOCTORDETAILS ORDER BY DRCODEDESC LIMIT 1";
$query=$this->db->query($sql1);
if (!$sql1) { // add this check.
die('Invalid query');
}
$output_array2=array();
foreach($query->result_array() as $row)
{
$ids=$row['DRCODE'];
}
// echo $ids;
if($ids){
$su=1;
$num =$num = 'DR' . str_pad($su + substr($ids, 3), 6, '0', STR_PAD_LEFT);;
$unique=$num;
}else{
$unique='DR000001';
}
You should make a different column fr drcode, leave it blank.
Now make a trigger on insert, it should be run after insert.
I am assuming DOCTORDETAILS as table name and drcode as column name
DELIMITER $$
CREATE TRIGGER trigger_after_insert
AFTER INSERT ON `DOCTORDETAILS` FOR EACH ROW
begin
UPDATE `DOCTORDETAILS` set drcode=CONCAT('DR',new.id);
END$$
DELIMITER ;
The trigger create a new string with your new auto generated id
Trigger in MySQL:
TechonTheNet
MySQL Trigger on after insert
I'm building an android app that uses Phil Sturgeon's RESTful Server for CodeIgniter as a RESTful API.
When the android app makes a POST request to register a user with facebook oauth data the method below is called when it reaches server side. It works, but if one or more of the optional params is empty it will insert a 0 into my database.
How do I prevent this? I'd much prefer it enters nothing at all or null.
function fb_register_post(){
if($this->get_request_method() != "POST"){
$this->response('',406);
}
$oauth_email = $this->input->post('OAUTH_EMAIL');
$oauth_uid = $this->input->post('OAUTH_UID');
$oauth_provider = $this->input->post('OAUTH_PROVIDER');
$first_name = $this->input->post('FIRST_NAME');
$last_name = $this->input->post('LAST_NAME');
if(!empty($oauth_provider) and !empty($oauth_uid) and !empty($oauth_email) and !empty($first_name) and !empty($last_name)){
if(filter_var($oauth_email, FILTER_VALIDATE_EMAIL)){
$new_member_insert_data = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $oauth_email,
'OAUTH_EMAIL' => $oauth_email,
'OAUTH_PROVIDER' => $oauth_provider,
'OAUTH_UID' => $oauth_uid,
//OPTIONAL DATA
'gender' => $this->post('GENDER'),
'hometown' => $this->post('HOMETOWN'),
'bio' => $this->post('BIO'),
'birthday' => $this->post('BIRTHDAY')
);
$this->load->model('membership_model');
$data['user'] = $register = $this->membership_model->oauth_register($new_member_insert_data);
$this->response($data, 200);
}
}else{
$message = array('message' => 'FAIL');
$this->response($message, 201);
}
$message = array('message' => 'FAIL!');
$this->response($message, 200); // 200 being the HTTP response code
}
The model function being called is :
function oauth_register($new_member_insert_data)
{
$insert = $this->db->insert('users', $new_member_insert_data);
if($insert){
$UID = $new_member_insert_data['OAUTH_UID'];
$q = $this->db->query("SELECT * FROM users WHERE OAUTH_UID = $UID LIMIT 1 ") or die(mysql_error());
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
else
{
return false;
}
}
The issue is your post parameters is passing an empty string '' for the value (at least that's what the $_POST array will see it as). Then you try to insert this into an numeric column and Mysql magically is casting it to 0 -- even if you've got another default value set.
The best thing you can do is check the parameters for being empty before adding them to the $new_member_insert_data array any values that are numeric (assuming this array is used to construct the insert statement). Below is an explicit example of not setting array members that have empty values:
//assuming all non-optional details have values
$new_member_insert_data = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $oauth_email,
'OAUTH_EMAIL' => $oauth_email,
'OAUTH_PROVIDER' => $oauth_provider,
'OAUTH_UID' => $oauth_uid
) ;
//OPTIONAL DATA
$gender = $this->post('GENDER')? $this->post('GENDER'):null;
if(!empty($gender)){
$new_member_insert_data['gender'] = $gender;
}
$hometown = $this->post('HOMETOWN')? $this->post('HOMETOWN'):null;
if(!empty($hometown)){
$new_member_insert_data['hometown'] = $hometown;
}
...etc...
You can also prevent this on the client request side by not putting any thing without an value into your post parameters, but I always protect against this on the webservice side, not just the client POST request side.
You'll also see this happen with dates and timestamps... when you try to set them to '' tehy end up like 0000-00-00 00:00:00.
You can turn on a strict mode in Mysql that will cause inserts fail when you try to stuff an empty string into a numeric field or other non-character field (I highly recommend against this though).