Can't get MySQL Update query to work with jsgrid - php

I currently have this code connected to a JSGrid table:
$connect = new PDO("mysql:host=localhost;dbname=localDatabase", "root", "root");
$method = $_SERVER['REQUEST_METHOD'];
$query = "SELECT COUNT(*) FROM stmr";
$link = mysqli_connect("localhost","root", "root", "localDatabase");
$result = mysqli_query($link, $query);
$form_id = mysqli_fetch_array($result)[0] + 1;
if($method == 'GET')
{
$data = array(
':item_id' => "%" . $_GET['item_id'] . "%",
':description' => "%" . $_GET['description'] . "%",
':part_number' => "%" . $_GET['part_number'] . "%",
':unit' => "%" . $_GET['unit'] . "%",
':quantity' => "%" . $_GET['quantity'] . "%"
);
$query = "SELECT * FROM stmrdesc WHERE item_id LIKE :item_id AND description LIKE :description AND part_number LIKE :part_number AND unit LIKE :unit AND quantity LIKE :quantity ORDER BY item_id DESC";
$statement = $connect->prepare($query);
$statement->execute($data);
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'id' => $row['row_id'],
'item_id' => $row['item_id'],
'description' => $row['description'],
'part_number' => $row['part_number'],
'unit' => $row['unit'],
'quantity' => $row['quantity']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
if($method == "POST")
{
$data = array(
':item_id' => $_POST['item_id'],
':description' => $_POST['description'],
':part_number' => $_POST["part_number"],
':unit' => $_POST["unit"],
':quantity' => $_POST["quantity"]
);
$query = "INSERT INTO stmrdesc (item_id, description, part_number, unit, quantity) VALUES (:item_id, :description, :part_number, :unit, :quantity)";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if($method == 'PUT')
{
parse_str(file_get_contents("php://input"), $_PUT);
$data = array(
':item_id' => $_PUT['item_id'],
':description' => $_PUT['description'],
':part_number' => $_PUT['part_number'],
':unit' => $_PUT['unit'],
':quantity' => $_PUT['quantity']
);
$query = "
UPDATE 'stmrdesc'
SET 'item_id' = ':item_id',
'description' = ':description',
'part_number' = ':part_number',
'unit' = ':unit',
'quantity' = ':quantity'
WHERE 'id' = ':id'
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if($method == "DELETE")
{
parse_str(file_get_contents("php://input"), $_DELETE);
$query = "DELETE FROM stmrdesc WHERE id = '".$_DELETE["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
}
As you can see, I have a method that is connected to each of the buttons of the JSGrid table and all work (submit the changes to the database) except the PUT Method that edits and updates the row in the database.

The put sql statement has WHERE 'id' = ':id' but ':id' does not exist in the $data array.

Related

How to insert a values into different table in a single php page?

I am inserting a record on my table after inserting to another table. This my sample code:
if(isset($_POST['submit'])){
$database = new Database();
$db = $database->getConnection();
$employee = new Employee($db);
if(!empty($first_name) && !empty($family_name) && !empty($first_name_arabic) && !empty($family_name_arabic)){
$emp_number = isset($_POST['emp_number']) && !empty($_POST['emp_number']) ? $_POST['emp_number'] : $employee->generateEmployeeNumber();
$fields = [
'reference' => $reference,
'emp_number' => $emp_number,
'first_name' => $first_name,
'middle_name' => $middle_name,
'third_name' => $third_name,
'family_name' => $family_name,
'nationality' => $nationality,
];
$employee->createOrUpdate($fields, '');
$result = $employee->selectOne('Reference', $reference);
if(!empty($_POST['passport_number']) && !empty($_POST['passport_place_issue']) && !empty($_POST['passport_date_issue']) && !empty($_POST['passport_date_expiry']) && !empty($result['id'])) {
$passport = new Passport($db);
$passport_fields = [
'passport_number' => $_POST['passport_number'],
'place_issue' => $_POST['passport_place_issue'],
'date_issue' => date_format(date_create($_POST['passport_date_issue']), 'Y-m-d'),
'date_expiry' => date_format(date_create($_POST['passport_date_expiry']), 'Y-m-d'),
'reference' => $result['reference'] ,
'employee_id' => $result['id'],
'status' => 'Active',
];
$passport->createOrUpdate($passport_fields, '');
}
}
}
but my problem is my insertion for passport table is not doing anything and no error is being return to me. As for the creatOrUpdate this is how i did:
function createOrUpdate($fields, $id){
if(is_null($id) || empty($id)){
$implodeColumns = implode(', ', array_keys($fields));
$implodePlaceholder = implode(", :", array_keys($fields));
$sql = "INSERT INTO " . $this->table_name. "($implodeColumns) VALUES(:".$implodePlaceholder.")";
echo "SQL ".$sql;
$stmt = $this->conn->prepare($sql);
foreach ($fields as $key => $value) {
$stmt->bindValue(":".$key,$value);
}
$stmt->execute();
}else{}
}
I don't know if creating a method with a same name is affecting the code, but createOeUpdate method for employee is from employee.php where createOrUpdate mehod for passport is from passport.php. Only employee is being saved in my database.
Any help is much appreciated
If the names are the same from different files you need to use namespaces like:
namespace name_of_your_main_file;
// Maybe need to add full path
// if it's not in the same folder.
use employee;
use passport;
// And use it with same names as:
employee::createOrUpdate(

Insert XML Data into Mysql Table Using PHP with Ajax

I am using the below PHP file to upload XML to MySQL database, but the issue is my table name is Con-1 and cannot use it.
I have error in the below line:
array(
':name' => $data->Con-1[$i]->name,
':address' => $data->Con-1[$i]->address,
':gender' => $data->Con-1[$i]->gender,
':designation' => $data->Con-1[$i]->designation,
':age' => $data->Con-1[$i]->age
)
please help me to solve it
<?php
//import.php
sleep(3);
$output = '';
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '')
{
$valid_extension = array('xml');
$file_data = explode('.', $_FILES['file']['name']);
$file_extension = end($file_data);
if(in_array($file_extension, $valid_extension))
{
$data = simplexml_load_file($_FILES['file']['tmp_name']);
$connect = new PDO('mysql:host=localhost;dbname=testing','root', '');
$query = "
INSERT INTO `Con-1`
(name, address, gender, designation, age)
VALUES(:name, :address, :gender, :designation, :age);
";
$statement = $connect->prepare($query);
for($i = 0; $i < count($data); $i++)
{
$statement->execute(
array(
':name' => $data->Con-1[$i]->name,
':address' => $data->Con-1[$i]->address,
':gender' => $data->Con-1[$i]->gender,
':designation' => $data->Con-1[$i]->designation,
':age' => $data->Con-1[$i]->age
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
$output = '<div class="alert alert-success">Import Data Done</div>';
}
}
else
{
$output = '<div class="alert alert-warning">Invalid File</div>';
}
}
else
{
$output = '<div class="alert alert-warning">Please Select XML File</div>';
}
echo $output;
?>
You should be able to do it using variable variables, so first assign Con-1 to a variable and then substitute this variable for the name in the assignment...
$var = 'Con-1';
$statement->execute(
array(
':name' => $data->$var[$i]->name,
':address' => $data->$var[$i]->address,
':gender' => $data->$var[$i]->gender,
':designation' => $data->$var[$i]->designation,
':age' => $data->$var[$i]->age
)
);

Update Query with PDO becames delete

I have a update query using PDO,
but when I execute it, it deletes my record.
public function update($e) {
$sql = 'UPDATE experiences SET company = :company, position = :position, duty = :duty WHERE id = :id';
//$this->operaction($sql, $e);
$id = $e['id'];
$company = $e['company'];
$position = $e['position'];
$duty = $e['duty'];
$pdostmt = $this->db->prepare($sql);
$pdostmt->bindValue(':id', $id, PDO::PARAM_INT);
$pdostmt->bindValue(':company', $company, PDO::PARAM_STR);
$pdostmt->bindValue(':position', $position, PDO::PARAM_STR);
$pdostmt->bindValue(':duty', $duty, PDO::PARAM_STR);
$pdostmt->execute();
}
$e is an array of $_POST array('id' => '6', 'company' => 'webcanada', 'position' => 'web developer', 'duty' => 'build website');
Can anyone suggest I have done wrong?
Thanks.

saving php array to mariadb dynamic colum

I have an array like this
$test = array(
'Subscription' => '1',
'Streaming' => '1',
'Download' => '0'
)
so during updating to mariaDB
$query = 'UPDATE table_1 set category_dynamic = COLUMN_CREATE(' . $test . ') where id = 1';
$this->Model->query($query);
I want to save the array this way ('Subscription',1,'Streaming',1,'Download',0)
any suggestion ?
You can try this :
<?php
$test = array(
'Subscription' => '1',
'Streaming' => '1',
'Download' => '0'
);
$data = '';
foreach($test as $key=>$value)
{
$data .= '"'.$key.'"'.', '.$value.', ';
}
$data = rtrim($data,', ');
$query = 'UPDATE table_1 set category_dynamic = COLUMN_CREATE(' . $data . ') where id = 1';
Hope it will solve the problem.
You could use a combination of array_map and implode for that.
$test = array(
'Subscription' => '1',
'Streaming' => '1',
'Download' => '0'
);
$list = implode(',', array_map(function ($v, $k) { return "'".$k."'" . ',' . $v; }, $test, array_keys($test)));
$query = 'UPDATE table_1 set category_dynamic = COLUMN_CREATE(' . $list . ') where id = 1';
$this->Model->query($query);

Can't access variable for unknown reason

I'm trying to execute two INSERT statements and I need the last inserted id to do so. I've tried $question_id = $dbh->lastInsertId();, but it doesn't work. Now I'm executing an additional SELECT LAST_INSERT_ID() statement, but that doesn't work either. I keep getting this error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined, which occurs because $question_id is empty because selecting the last insert id doesn't seem to work.
Here's my code:
public function add_question($user_id, $group_id, $title, $caption, $datetime, $status) {
// Add user to database
try {
$dbh = new DBHandler();
$sql =
"INSERT INTO question(
user_id,
group_id,
title,
caption,
created_date_time,
question_status
)
VALUES(
:user_id,
:group_id,
:title,
:caption,
:created_date_time,
:question_status
)";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute(
array(
':user_id' => $user_id,
':group_id' => $group_id,
':title' => $title,
':caption' => $caption,
':created_date_time' => $datetime,
':status' => $status
)
);
//$question_id = $dbh->lastInsertId();
$sql= "SELECT LAST_INSERT_ID() AS question_id";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute();
// Resultset
$result = $stmt->fetchAll();
foreach($result AS $question_id_row) {
$question_id = $question_id_row['question_id'];
}
$sql =
"INSERT INTO notification(
n_question_id,
n_question_user_id,
n_question_group_id,
n_question_title
)
VALUES(
:n_question_id,
:n_question_user_id,
:n_question_group_id,
:n_question_title
)";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute(
array(
':n_question_id' => $question_id,
':n_question_user_id' => $user_id,
':n_question_group_id' => $group_id,
':n_question_title' => $title
)
);
echo 'Question added!';
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
Your query fails with invalid number of parameter and parameter was not defined because you define this parameter
:question_status
but you bind
':status' => $status
change
$stmt->execute(
array(
':user_id' => $user_id,
':group_id' => $group_id,
':title' => $title,
':caption' => $caption,
':created_date_time' => $datetime,
':question_status' => $status //here
)
);
and it will work

Categories