I am using Opencart v2.2.0 and I am having problem with my php script. The line in question is:
$stmt2->bind_param('sssssisi', $name, $description, $meta_description, $meta_keyword, $tag, $modified_by, $product_id, $language_id);
The whole function including the line above is as follows:
function restoreBackup()
{
global $mysqli;
$i = 0;
$getpic = "SELECT * FROM oc_product_backup LIMIT 0, 100000";
$backup = $mysqli->query($getpic);
$mysqli->autocommit(FALSE);
$updateproduct_sql = "UPDATE oc_product SET image = ?, ean = ?, model = ?, status = ?, price_sync = ?, modified_by = ?, date_modified = ? WHERE product_id= ?";
$updatedescription_sql = "UPDATE oc_product_description SET name = ?, description = ?, meta_description = ?, meta_keyword = ?, tag = ?, modified_by = ? WHERE product_id = ? AND language_id = ?";
$stmt = $mysqli->prepare($updateproduct_sql);
$stmt->bind_param('sssiiiss', $image, $ean, $model, $status, $price_sync, $modified_by, $date_modified, $product_id);
$stmt2 = $mysqli->prepare($updatedescription_sql);
$stmt2->bind_param('sssssisi', $name, $description, $meta_description, $meta_keyword, $tag, $modified_by, $product_id, $language_id);
while($row = $backup->fetch_array(MYSQLI_ASSOC))
{
//$name = removeslashes($row['name']);
$name = $row['name'];
//$description = removeslashes($row['description']);
$description = $row['description'];
$meta_description = $row['meta_description'];
$meta_keyword = $row['meta_keyword'];
$tag = $row['tag'];
$product_id = $row['product_id'];
$modified_by = $row['modified_by'];
$language_id = $row['language_id'];
if($row['language_id'] == 4)
{
$image = $row['image'];
$ean = $row['ean'];
$name = $row['name'];
$model = $row['model'];
$status = $row['status'];
$price_sync = $row['price_sync'];
$date_modified = $row['date_modified'];
if(!$stmt->execute())
return false;
}
if(!$stmt2->execute())
return false;
$i++;
if(($i % 500) === 0) $mysqli->commit();
}
$mysqli->commit();
$backup->close();
return true;
}
function removeslashes($string)
{
$string=implode("",explode("\\",$string));
return stripslashes(trim($string));
}
The error I get is
Fatal error: Call to a member function bind_param() on boolean in
Any suggestions, please? I do not see what am I doing wrong. Thank you all in advance.
The prepare() method can return false and you should check for that. As for why it returns false, perhaps the table name or column names (in SELECT, UPDATE or WHERE clause) are not correct?
Also, consider use of something like $query->error_list to examine errors that occurred parsing the SQL. (I'll occasionally echo the actual SQL statement strings and paste into phpMyAdmin to test, too, but there's definitely something failing there.)
Related
I have a function in my PHP script which restores data from backup. Everything was fine and working well, until suddenly it stopped working after months of working well. I am using OC 2.2.0 and this function is supposed to restore products and their data from oc_product_backup table. I print_r every step so that I would see where the problem is, and realized that when it gets to:
return true;
it never happens. What could be wrong all of the sudden, and how do I make this work? I never had this kind of problem. My function looks like this:
function restoreBackup()
{
global $mysqli;
$i = 0;
$getpic = "SELECT * FROM oc_product_backup LIMIT 0, 100000";
$backup = $mysqli->query($getpic);
$mysqli->autocommit(FALSE);
$updateproduct_sql = "UPDATE oc_product SET image = ?, modified_by = ?, date_modified = ? WHERE product_id= ?";
$updatedescription_sql = "UPDATE oc_product_description SET meta_description = ?, meta_keyword = ?, tag = ?, modified_by = ? WHERE product_id = ? AND language_id = ?";
$stmt = $mysqli->prepare($updateproduct_sql);
$stmt->bind_param('siss', $image, $modified_by, $date_modified, $product_id);
//print_r ($updateproduct_sql);
$stmt2 = $mysqli->prepare($updatedescription_sql);
$stmt2->bind_param('sssisi', $meta_description, $meta_keyword, $tag, $modified_by, $product_id, $language_id);
//print_r($updatedescription_sql);
while($row = $backup->fetch_array(MYSQLI_ASSOC))
{
//$name = removeslashes($row['name']);
//$name = $row['name'];
//$description = removeslashes($row['description']);
//$description = $row['description'];
$meta_description = $row['meta_description'];
$meta_keyword = $row['meta_keyword'];
$tag = $row['tag'];
$product_id = $row['product_id'];
$modified_by = $row['modified_by'];
$language_id = $row['language_id'];
//if($row['language_id'] == 1)
//{
$image = $row['image'];
//$ean = $row['ean'];
//$name = $row['name'];
//$model = $row['model'];
//$status = $row['status'];
$price_sync = $row['price_sync'];
$date_modified = $row['date_modified'];
if(!$stmt->execute())
return false;
//}
if(!$stmt2->execute())
return false;
$i++;
if(($i % 500) === 0) $mysqli->commit();
}
$mysqli->commit();
$backup->close(); //the last line that gets executed
return true; //this never happens
writeToLog('- Backup restored');
}
After looking at the code a bit, it seems like your prepared statements binding the data was outside of the loop, so technically it would never have written any data.
function restoreBackup() {
global $mysqli;
$i = 0;
$getpic = "SELECT * FROM oc_product_backup LIMIT 0, 100000";
$backup = $mysqli - > query($getpic);
$mysqli - > autocommit(FALSE);
$updateproduct_sql = "UPDATE oc_product SET image = ?, modified_by = ?, date_modified = ? WHERE product_id= ?";
$updatedescription_sql = "UPDATE oc_product_description SET meta_description = ?, meta_keyword = ?, tag = ?, modified_by = ? WHERE product_id = ? AND language_id = ?";
while ($row = $backup - > fetch_array(MYSQLI_ASSOC)) {
$meta_description = $row['meta_description'];
$meta_keyword = $row['meta_keyword'];
$tag = $row['tag'];
$product_id = $row['product_id'];
$modified_by = $row['modified_by'];
$language_id = $row['language_id'];
$image = $row['image'];
$price_sync = $row['price_sync'];
$date_modified = $row['date_modified'];
$stmt = $mysqli - > prepare($updateproduct_sql);
$stmt - > bind_param('siss', $image, $modified_by, $date_modified, $product_id);
if (!$stmt - > execute())
return false;
$stmt2 = $mysqli - > prepare($updatedescription_sql);
$stmt2 - > bind_param('sssisi', $meta_description, $meta_keyword, $tag, $modified_by, $product_id, $language_id);
if (!$stmt2 - > execute())
return false;
$i++;
if (($i % 500) === 0) $mysqli - > commit();
}
$mysqli - > commit();
$backup - > close(); //the last line that gets executed
return true; //this never happens
writeToLog('- Backup restored');
}
Hi I'm trying to update my tbl_jadwal, it said success, but database is not updated, anybody can please help me finding where the problem is ? Thankyou
<?php
if (isset($_GET['id'])) {
$ID = $_GET['id'];
} else {
$ID = "";
}
// create array variable to store category data
$category_data = array();
$sql_query = "SELECT Category_ID, Category_name
FROM tbl_category
ORDER BY Category_ID ASC";
$stmt_category = $connect->stmt_init();
if ($stmt_category->prepare($sql_query)) {
// Execute query
$stmt_category->execute();
// store result
$stmt_category->store_result();
$stmt_category->bind_result($category_data['Category_ID'],
$category_data['Category_name']
);
}
$sql_query = "SELECT Menu_image FROM tbl_jadwal WHERE Menu_ID = ?";
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $ID);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($previous_menu_image);
$stmt->fetch();
$stmt->close();
}
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->fetch();
$stmt->close();
}
if (isset($_POST['btnEdit'])) {
$nama_lokasi = $_POST['nama_lokasi'];
$category_ID = $_POST['category_ID'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$description = $_POST['description'];
// get image info
$menu_image = $_FILES['menu_image']['name'];
$image_error = $_FILES['menu_image']['error'];
$image_type = $_FILES['menu_image']['type'];
// create array variable to handle error
$error = array();
// updating all data
$sql_query = "UPDATE tbl_jadwal
SET Nama_Lokasi = ? , Category_ID = ?, Latitude = ?, Longitude = ?, Phone = ?, Email = ?, Menu_image = ?, Description = ?
WHERE Menu_ID = ?";
$upload_image = 'upload/images/' . $menu_image;
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('ssssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$upload_image,
$description,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
} else {
updating all data except image file
$sql_query = "UPDATE tbl_jadwal
SET Nama_Lokasi = ? , Category_ID = ?,
Longitude = ?, Latitude = ?, Phone = ?, Email = ?, Description = ?
WHERE Menu_ID = ?";
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('sssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$description,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
}
check update result
if ($update_result) {
$error['update_data'] = " <span class='label label-primary'>Success update</span>";
} else {
$error['update_data'] = " <span class='label label-danger'>failed update</span>";
}
This my database structure
replace bind_param() with bindParam(':data', $data);
or try $stmt->execute(array(':data' => $data))
Hi Just write the simple query firstly and add EXPLAIN before it.
For example:
EXPLAIN update table set name='test' where id=1;
This statement will show all the possible error. In this way you will be able to resolve the problem.
Trying to integrate a new script with my existing homepage I am required to include 2 new php files in my index.php. I love playing with web development but sadly my coding knowlage is very limited. (CMS and GUI make human stupid)
if ($page == 'Premium') {
include('affiliates/controller/affiliate-tracking.php');
if (isset($_GET['payment']) && $_GET['payment'] == 'created') {
$sale_amount = '5.00';
$product = 'Premium';
include('affiliates/controller/record-sale.php');
}
}
If I do this I get the fatal error: Call to a member function fetch_assoc() on a non-object in affiliates/controller/record-sale.php on line 61.
Code in line 61 is this:
$stmt->execute();
Can someone Point me in the right direction here? I am not really sure what the error means. There don't seem to be any database errors and all the other functions work the way they are supposed to.
Thanks to any samaritan who answers.
Using mysqli
complete code for record-sale.php is this:
application/x-httpd-php record-sale.php ( PHP script text )
<?php
$path = dirname(__FILE__);
$path = substr($path, 0, -10);
include($path.'/auth/db-connect.php');
$ap_tracking = 'ap_ref_tracking';
$datetime = date("Y-m-d H:i:s");
//IF AFFILIATE ID IS PRESENT
if(isset($_COOKIE[$ap_tracking])){
session_start();
//GET COMMISSION LEVEL
$get_dc = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT default_commission FROM ap_settings WHERE id=1"));
$default_commission = $get_dc['default_commission'];
//IS SALE VOLUME COMMISSIONS ON
$get_sv = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT sv_on FROM ap_other_commissions WHERE id=1"));
$sv_on = $get_sv['sv_on'];
if($sv_on=='1'){
$get_cl = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT percentage FROM ap_commission_settings WHERE $sale_amount BETWEEN sales_from AND sales_to"));
$comission = $get_cl['percentage'];
}
//COMMISSION OVERRIDE
$comission = $commission;
//SET DEFAULT COMMISSION IF NO OTHER VALUE HAS BEEN SET
if($comission==''){$comission = $default_commission;}
//RECURRING COMMISSIONS
if(isset($recurring)){
$recurring_period = strtolower($recurring);
$recurring_amount = $recurring_fee;
if($recurring_period==''){$recurring_period='monthly';}
if($recurring_fee==''){$recurring_fee = $default_commission;}
}else{
$recurring_period = 'Non-recurring';
$recurring_fee = '0';
}
//RECORD SALE
$affiliate_id = $_COOKIE[$ap_tracking];
$percentage = $comission / 100;
$net_earnings = $sale_amount * $percentage;
$datetime = date("Y-m-d H:i:s");
//CHECK FOR VALID AFFILIATE
$get_affiliate = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT balance FROM ap_members WHERE id=$affiliate_id"));
$affiliate_balance = $get_affiliate['balance'];
if(isset($affiliate_balance)){
//PREVENT DUPLICATE SALES
if($_SESSION['ap_sale_hit']=='1' && $affiliate_id == $_SESSION['saved_affiliate'] && $net_earnings == $_SESSION['saved_net']){}else{
$stmt = $mysqli->prepare("INSERT INTO ap_earnings (affiliate_id, product, comission, sale_amount, net_earnings, recurring, recurring_fee, datetime) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssssss', $affiliate_id, $product, $comission, $sale_amount, $net_earnings, $recurring_period, $recurring_fee, $datetime);
$stmt->execute();
$transaction_id = $stmt->insert_id;
$stmt->close();
//UPDATE AFFILIATE BALANCE
$updated_balance = $affiliate_balance + $net_earnings;
$update_one = $mysqli->prepare("UPDATE ap_members SET balance = ? WHERE id=$affiliate_id");
$update_one->bind_param('s', $updated_balance);
$update_one->execute();
$update_one->close();
}
}
//MULT-TIER COMMISSIONS
$get_mt = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT mt_on FROM ap_other_commissions WHERE id=1"));
$mt_on = $get_mt['mt_on'];
if($mt_on=='1'){
$levels = 10;
//FOR EACH LEVEL RUN
$get_sponsor = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT sponsor FROM ap_members WHERE id=$affiliate_id"));
$sponsor = $get_sponsor['sponsor'];
for ($loop = 2 ; $loop < $levels; $loop++){
//CHECK FOR AVAILABLE SPONSOR
if($sponsor!='0'){
//GET LEVEL PERCENTAGE
$gp = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_other_commissions WHERE id=1"));
$p = $gp['tier'.$loop.''];
$sc = $p / 100;
$se = $sale_amount * $sc;
//GET SPONSOR BALANCE
$gb = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT balance FROM ap_members WHERE id=$sponsor"));
$ob = $gb['balance'];
$nb = $ob + $se;
$update_one = $mysqli->prepare("UPDATE ap_members SET balance = ? WHERE id=$sponsor");
$update_one->bind_param('s', $nb);
$update_one->execute();
$update_one->close();
//INSERT TRANSACTION HISTORY
$stmt = $mysqli->prepare("INSERT INTO ap_multi_tier_transactions (affiliate_id, transaction_id, tier, commission, mt_earnings, datetime) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $sponsor, $transaction_id, $loop, $p, $se, $datetime);
$stmt->execute();
$stmt->close();
}else{
break 1;
}
//GET NEXT SPONSOR FOR NEXT LOOP
$gs = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT sponsor FROM ap_members WHERE id=$sponsor"));
$sponsor = $gs['sponsor'];
}
}
$_SESSION['ap_sale_hit'] = '1';
$_SESSION['saved_affiliate'] = $affiliate_id;
$_SESSION['saved_net'] = $net_earnings;
}
if(isset($_POST['reset'])){
unset($_SESSION['ap_sale_hit']);
unset($_SESSION['saved_affiliate']);
unset($_SESSION['saved_net']);
//header("Refresh:0");
}
?>
I have this script:
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors','1');
ini_set('default_charset','utf-8');
include("includes/mysqli.php");
$con->set_charset("utf8");
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement
$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);
$stmts = $con->prepare("SELECT * FROM activeclans WHERE id > 137439657919 ORDER BY id ASC"); //Prepare select statement
$stmts->execute(); //execute select statement
$result = $stmts->get_result(); //get select statement results
while ($row = $result->fetch_assoc()) {
$clanid = $row['id'];
$clanurl = "http://185.112.249.77:9999/Api/clan?clan=$clanid";
$jsondata = file_get_contents($clanurl);
$data = json_decode($jsondata,true);
if($data['name'] != null){
$name = $data['name'];
}else{
$name = "";
}
$badge = $data['badge'];
if($data['status'] != null){
$status = $data['status'];
}else{
$status = "";
}
$playercount = $data['playerCount'];
$score = $data['score'];
$requiredtrophies = $data['requiredTrophies'];
$warswon = $data['warsWon'];
$warslost = $data['warsLost'];
$warstied = $data['warsTied'];
if($data['clanLocation'] != null){
$location = $data['clanLocation'];
}else{
$location = "";
}
if($data['warFrequency'] != null){
$warfrequency = $data['warFrequency'];
}else{
$warfrequency = "";
}
$exp = $data['exp'];
$level = $data['level'];
$description = $data['description'];
$playerarray = json_encode($data['players']);
/* Execute update statement */
$stmt->execute();
}
echo $stmt->affected_rows;
$stmt->close();
$stmts->close();
$con->close();
?>
And it is basically inserting around 157K (157 THOUSAND) rows of data. And the data is quite big as well! You can't check the file_get_contents URL out because the port is open only to localhost.
What is the quickest way to insert all this data? It has been running for almost 24 hours now and done 65K. I did try and use transactions but that didn't work well. It gave my 502 Bad Gateway and therefore I lost a lot of time on the script because it rolled back after adding 3 thousand rows (which was however quite quick!)
Also it is possible that the script may at some point fail and leave some of the varchar fields as null hence I have made it so that they end up as an empty string so that there aren't any mySql errors (I got those exceptions thrown when using transactions)
This is the code I used with the transaction stuff. I'm pretty new to prepared statements. I converted this code from standard queries to prepared today and then tried transactions.
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors','1');
ini_set('default_charset','utf-8');
include("includes/mysqli.php");
$con->set_charset("utf8");
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement
$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);
$stmts = $con->prepare("SELECT * FROM activeclans WHERE id > 137439657919 ORDER BY id ASC"); //Prepare select statement
$stmts->execute(); //execute select statement
$result = $stmts->get_result(); //get select statement results
try{
$con->autocommit(FALSE);
while ($row = $result->fetch_assoc()) {
$clanid = $row['id'];
$clanurl = "http://185.112.249.77:9999/Api/clan?clan=$clanid";
$jsondata = file_get_contents($clanurl);
$data = json_decode($jsondata,true);
if($data['name'] != null){
$name = $data['name'];
}else{
$name = "";
}
$badge = $data['badge'];
if($data['status'] != null){
$status = $data['status'];
}else{
$status = "";
}
$playercount = $data['playerCount'];
$score = $data['score'];
$requiredtrophies = $data['requiredTrophies'];
$warswon = $data['warsWon'];
$warslost = $data['warsLost'];
$warstied = $data['warsTied'];
if($data['clanLocation'] != null){
$location = $data['clanLocation'];
}else{
$location = "";
}
if($data['warFrequency'] != null){
$warfrequency = $data['warFrequency'];
}else{
$warfrequency = "";
}
$exp = $data['exp'];
$level = $data['level'];
$description = $data['description'];
$playerarray = json_encode($data['players']);
/* Execute update statement */
if(!$stmt->execute()){
throw new Exception("Cannot insert record. Reason :".$stmt->error);
}
}
$con->commit();
}catch (Exception $e) {
echo 'Transaction failed: ' . $e->getMessage();
$con->rollback();
}
echo $stmt->affected_rows;
$stmt->close();
$stmts->close();
$con->close();
?>
Thanks :)
$sql="
INSERT INTO
ue_game_alliance_rank_rights
(
rank
, `right`
)
VALUES
";
$insertQuery = array();
$insertData = array();
foreach ($rights_status['add'] AS $row ) {
$insertQuery[] = '(?,?)';
$insertData[] = $rank;
$insertData[] = $row['id'];
}
if (!empty($insertQuery)) {
$sql .= implode(', ', $insertQuery);
$stmt = $this->db->prepare($sql);
$stmt->execute($insertData);
}
}
That's an example of the basic technique, you would need to swap the functions for their equivalent mysqli_* functions. For each field having data inserted into it, you need:
$insertData[] = $row['id'];
$row needs to match whatever you've used in your foreach loop and ['id'] needs to be whatever the name of the field is that you're inserting into.
$insertQuery[] = '(?,?)';
You need as many placeholders as fields that you'll be inserting into.
Overall it creates a bulk insert, so you need to have the data to be inserted in an array. Given the amount of data that you're inserting, use transactions, you'll probably need to experiment to see how many rows you can bulk insert at a time before the server complains
I have a little problem when I try to validating the condition in my insert method.
This is what I want :
if data not exist, do insert data
if data exist in 'isActive' is 'true', send error 'data already exist'
if data exist in 'isActive' is 'false', run update method
But it seems my method can not run smoothly.
this is my insert method :
public function InsertUserCard(UserCard $uc)
{
//get kartu
$user_card = $this->GetUserCardByCardIdByUserId($uc);
if(!$user_card)
{
$stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
(user_card_id, user_id, card_id, card_number, barcode, barcode_format, created_at, updated_at)
VALUES('', ?, ?, ?, ?, ?, ?, ?)");
if ($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$user_id = NULL;
$card_id = NULL;
$card_number = NULL;
$barcode = NULL;
$barcode_format = NULL;
$created_at = NULL;
$updated_at = NULL;
$stmt->bind_param("iisssss", $user_id, $card_id, $card_number, $barcode, $barcode_format, $created_at, $updated_at);
$user_id = $uc->getUserId();
$card_id = $uc->getCardId();
$card_number = $uc->getCardNumber();
$barcode = $uc->getBarcode();
$barcode_format = $uc->getBarcodeFormat();
$created_at = $uc->getCreatedAt();
$updated_at = $uc->getUpdatedAt();
$stmt->execute();
$result = $this->conn->insert_id;
$stmt->close();
}
// Check for successful insertion
if ($result)
{
// User card successfully inserted
return $result;
}
else
{
// Failed to insert user card
return USER_CARD_INSERT_FAILED;
}
}
else if($user_card->getisActive() == 'true')
{
return USER_CARD_ALREADY_EXISTED;
}
else {
// this is where I try to run the update method
$uc->setUserCardId($user_card->getUserCardId());
$this->UpdateUserCard($uc);
return $uc->getUserCardId();
}
}
in last condition, I try to run the update method if the data is exists but 'isActive' value is 'false'
This is my update method :
public function UpdateUserCard(UserCard $uc)
{
$stmt = $this->conn->prepare("UPDATE ".$this->table_name."
SET user_id = ?,
card_id = ?,
card_number = ?,
barcode = ?,
barcode_format = ?,
isActive = ?,
updated_at = ?
WHERE user_card_id = ?
AND user_id = ?");
if($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$user_id = NULL;
$card_id = NULL;
$card_number = NULL;
$barcode = NULL;
$format = NULL;
$isActive = NULL;
$updated_at = NULL;
$user_card_id = NULL;
$stmt->bind_param("iisssssii", $user_id,
$card_id,
$card_number,
$barcode,
$format,
$isActive,
$updated_at,
$user_card_id,
$user_id);
$user_id = $uc->getUserId();
$card_id = $uc->getCardId();
$card_number = $uc->getCardNumber();
$barcode = $uc->getBarcode();
$format = $uc->getBarcodeFormat();
$isActive = $uc->getisActive();
$updated_at = $uc->getUpdatedAt();
$user_card_id = $uc->getUserCardId();
$stmt->execute();
$num_affected_rows = $stmt->affected_rows;
$stmt->close();
return $num_affected_rows > 0;
}
// Check for successful insertion
if ($stmt->execute())
{
// User card successfully inserted
return USER_CARD_INSERTED_SUCCESSFULLY;
}
else
{
// Failed to insert user card
return USER_CARD_INSERT_FAILED;
}
}
and the last is my GetUserCardByCardIdByUserId Method :
private function GetUserCardByCardIdByUserId(UserCard $card)
{
$stmt = $this->conn->prepare("SELECT user_card_id, user_id, card_id, card_number, barcode, barcode_format, isActive, created_at, updated_at
FROM ". $this->table_name ."
WHERE card_id = ? AND user_id = ?");
if ($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$card_id = NULL;
$user_id = NULL;
$stmt->bind_param("ii", $card_id, $user_id);
$card_id = $card->getCardId();
$user_id = $card->getUserId();
$stmt->execute();
$stmt->bind_result($user_card_id,
$user_id,
$card_id,
$card_number,
$barcode,
$barcode_format,
$isActive,
$created_at,
$updated_at);
$stmt->store_result();
$num_rows = $stmt->num_rows;
if($num_rows != 1)
return NULL;
else {
$card = new UserCard();
$card->setUserCardId($user_card_id);
$card->setUserId($user_id);
$card->setCardId($card_id);
$card->setBarcode($barcode);
$card->setBarcodeFormat($barcode_format);
$card->setisActive($isActive);
$card->setCreatedAt($created_at);
$card->setUpdatedAt($updated_at);
$stmt->close();
return $card;
}
}
}
please check my method if I write wrong structure of code.
thanks :)