Below this function, I did unlink one image. now I want to unlink one more image in this function Like "imagetwo".
How can write code in this function for unlink imagetwo?
public function nameDeleteById($data){
$delete_id = $data['delete_id'];
$stmt = $this->pdo->prepare("SELECT * FROM name WHERE id=:delete_id");
$stmt->bindparam(":delete_id", $delete_id);
$stmt->execute();
if ($stmt) {
while ($delimg=$stmt->fetch(PDO::FETCH_ASSOC)) {
$dellink=$delimg['image'];
unlink($dellink);
}
}
$stmt=$this->pdo->prepare("DELETE FROM name WHERE id=:delete_id");
$stmt->bindparam(":delete_id", $delete_id);
$stmt->execute();
if ($stmt) {
$msg = 'Name Deleted Secessfully';
return $msg;
} else {
$msg = 'Name Not Deleted Secessfully';
return $msg;
}
}
It is not clear from your question, what imagetwo exactly is. I'm assuming it is another column in the name table (?). If so, you can enhance your function like so:
public function nameDeleteById($data){
$delete_id = $data['delete_id'];
$stmt = $this->pdo->prepare("SELECT * FROM name WHERE id=:delete_id");
$stmt->bindparam(":delete_id", $delete_id);
$stmt->execute();
if ($stmt) {
while ($delimg=$stmt->fetch(PDO::FETCH_ASSOC)) {
unlink($delimg['image']);
unlink($delimg['imagetwo']);
}
}
$stmt=$this->pdo->prepare("DELETE FROM name WHERE id=:delete_id");
$stmt->bindparam(":delete_id", $delete_id);
$stmt->execute();
if ($stmt) {
$msg = 'Name Deleted Successfully';
return $msg;
} else {
$msg = 'Name Not Deleted Successfully';
return $msg;
}
}
Related
I have 2 tables in My database and I want to move data from one table to another table.
columns are
question_answer= id,question,answer,added_by,added_on
and
unknown_question=id,question,answer,added_on
On a button click, I want to move data from unknown_question to question_answer So below is my update question function which is currently working.
function updateQuestion($question_id)
{
if (canUpdateQuestion()) {
global $errors, $question, $answer, $isEditting; // pull in global form variables into function
$errors = validateUnknownQuestion($_POST, ['update_question','answer']); // validate form
if (count($errors) === 0) {
// receive form values
$question = $_POST['question'];
$answer = $_POST['answer'];
$sql = "UPDATE unknown_question SET question=?, answer=? WHERE id=?";
$result = modifyRecord($sql, 'ssi', [$question, $answer, $question_id]);
if ($result) {
$_SESSION['success_msg'] = "Unknown Question successfully updated". CHECKMARK;
$isEditting = false;
header("location: " . BASE_URL . "pages-unknown-question-list.php");
exit(0);
} else {
$_SESSION['error_msg'] = "Something went wrong. Could not save Unknown question in Database";
}
}
} else {
$_SESSION['error_msg'] = "You do not have permission to Edit Unknown question!!";
header("location: " . BASE_URL . "pages-unknown-question-list.php");
exit(0);
}
}
here what I am trying
// ACTION: Move question
if (isset($_GET['move_question'])) {
$question_id = $_GET['delete_question'];
deleteQuestion($question_id);
}
function moveToMainQuestion($question_id)
{
if (canUpdateQuestion()) {
global $question// pull in global form variables into function
$sql = "INSERT INTO question_answer SELECT question , answer FROM unknown_question WHERE id=?";
$result = modifyRecord($sql, 'i', [$question_id]);
if ($result) {
$sql = "DELETE FROM unknown_question WHERE id=?";
$result = modifyRecord($sql, 'i', [$question_id]);
if ($result) {
$_SESSION['success_msg'] = "Question Moved successfully". CHECKMARK;
header("location: " . BASE_URL . "pages-unknown-question-list.php");
exit(0);
}
} else {
$_SESSION['error_msg'] = "Something went wrong. Could not save Unknown question in Database";
}
} else {
$_SESSION['error_msg'] = "You do not have permission to Edit Unknown question!!";
header("location: " . BASE_URL . "pages-unknown-question-list.php");
exit(0);
}
}
And my prepare medhod
function modifyRecord($sql, $types, $params)
{
global $conn;
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$result = $stmt->execute();
$stmt->close();
return $result;
}
Hi I am creating an android app and made a fetch API that can get the converted json data
Here's my code
lib.php
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$userRows = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
and on my fetch_api.php
<?php
require_once '../database/database.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// edittext from android
$username = $_POST['username'];
$arr = array();
if($user->fetchUserData($username))
{
$arr['success'] = 1;
$arr['message'] = "Success fetching data";
echo json_encode($arr);
}
else
{
$arr['success'] = 0;
$arr['message'] = "Failed fetching data";
echo json_encode($arr);
}
}
?>
Right now I can successfully get the
{
"success": 1,
"message": "Success fetching data"
}
Now I want to display all of my data like fullname, address, phonenumber etc to be displayed .
When I am trying to do it like this
lib.php
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$userRows = $stmt->fetch(PDO::FETCH_ASSOC);
if($userRows)
{
$response["success"] = 1;
$response["message"] = "User Profile";
$response["user"] = array();
foreach($userRows as $rows)
{
$user = array();
$user["username"] = $rows['username'];
$user["fullname"] = $rows['fullname'];
array_push($response["user"], $user);
}
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Failed Fetching";
die(json_encode($response));
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
It's giving me the error saying
illegal string offset warning on username and fullname
I hope I am clear on my problem . Please ask me if my question is not clear so I can edit my question . Thank you.
ADDED
when I directly use json_encode like this
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$userRows = $stmt->fetch(PDO::FETCH_ASSOC);
json_encode($userRows);
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
it gives me this result
{"success":0,"message":"Failed fetching data"}
As I understand the problem that you are facing is how to return rows from the class methods, when it should only return true on success and false on fail.
You got something like that:
<?php
class user{
...
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$userRows = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
...
}
?>
You need to add a public property like $userRows to it and assign that property with your method:
class user{
public $userRows; // added here
...
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$this->userRows = $stmt->fetch(PDO::FETCH_ASSOC); // changed here
And after that you can:
<?php
...
if($user->fetchUserData($username)){
echo json_encode($user->userRows);
}else{
echo "error occured";
}
Hopefully it helped.
When i click first time inserting new data second time click that time it is not checking
function post($payload)
{
$stmt = $this->db->prepareQuery("SELECT * FROM user WHERE emailId= ? or phone= ?");
$stmt->bind_param('ss', $payload->email, $payload->phone);
$stmt->execute();
$result = $stmt->get_result();
while ($rows=$result->fetch_assoc())
{
if($rows['emailId']!=$payload->email || $rows['phone']!=$payload->phone)
{
$stmt = $this->db->prepareQuery("insert into user(emailId,phone,name,city,category_id,password) values(?,?,?,?,?,?)");
$stmt->bind_param('ssssds', $payload->email, $payload->phone, $payload->name, $payload->city, $payload->categ, $payload->pwd);
$stmt->execute();
$stmt->close();
$this->db->commit();
return $payload;
}
else
{
$stmt->close();
echo "Already existed";
return $payload;
}
}
}
You are checking for the record like you know its going to be in the first row. How about introduce another variable say $duplicate
$duplicate = false;
while ($rows=$result->fetch_assoc())
{
if($rows['emailId']==$payload->email || $rows['phone']==$payload->phone)
{
$duplicate = true;
break;
}
}
if(!$duplicate){
$stmt = $this->db->prepareQuery("insert into
user(emailId,phone,name,city,category_id,password) values(?,?,?,?,?,?)");
$stmt->bind_param('ssssds', $payload->email, $payload->phone, $payload->name,
$payload->city, $payload->categ, $payload->pwd);
$stmt->execute();
$stmt->close();
}
else{
echo "Duplicate";
}
here is my code for optverify.php if the input number is wrong its redirect to index.php its not giving error.its should give a error for wrong otp but please help me to solve this issue
<?php
// Create a unique instance of your session variables
session_start();
if(isset($_SESSION['usr_id']))
{
$uid=$_SESSION['usr_id'];
} else {
header("Location:login.php");
}
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
if (isset($_POST['verifyotp'])) {
$otpsms = $_POST['smsotp'];
$otpemail = $_POST['emailotp'];
$user = $db->verifyotp($uid);
if($user){
$user['smsotp'] = $otpsms;
$user['emailotp'] = $otpemail;
header("Location:index.php");
} else {
$errormsg = "Invalid otp";
}
}
?>
and my codes for data base function are below
public function verifyotp($uid){
$stmt = $this->con->prepare("SELECT uid,smsotp,emailotp FROM users WHERE uid = '$uid'");
$stmt->bind_param("i", $uid);
if ($stmt->execute()) {
$stmt->bind_result($uid,$smsotp,$emailotp);
$stmt->fetch();
$user = array();
$user["uid"] = $uid;
$user["smsotp"] = $smsotp;
$user["emailotp"] = $emailotp;
$stmt->close();
return $user;
} else
{
return $stmt;
}
}
Not tested but this should work !! Let me know if this doesn't work. will delete this answer.
Updated
Change this $user = $db->verifyotp($uid); to $user = $db->verifyotp($uid, $otpsms, $otpemail);
then modify your function like below if you are willing to test 3 parameters (1) id (2) smsotp (3) emailotp.
public function verifyotp($uid, $sotp, $eotp){
$stmt = $this->con->prepare("SELECT uid,smsotp,emailotp FROM users WHERE uid = '$uid' And smsotp='$sotp' And emailotp ='$eotp'");
$stmt->bind_param("i", $uid);
if ($stmt->execute()) {
$stmt->bind_result($uid,$smsotp,$emailotp);
$stmt->fetch();
$user = array();
$user["uid"] = $uid;
$user["smsotp"] = $smsotp;
$user["emailotp"] = $emailotp;
$stmt->close();
return $user;
} else
{
return $stmt;
}
}
I am very new to php and this is my first attempt at using mysqli. I can't seem to figure out why I am getting this error? I have reviewed similar questions on it but I still don't understand what the problem is.
Here is my code:
<?php
require_once('abstractDAO.php');
class customerDAO extends abstractDAO {
function __construct() {
try{
parent::__construct();
} catch(mysqli_sql_exception $e){
throw $e;
}
}
public function getCustomers(){
//The query method returns a mysqli_result object
$result = $this->mysqli->query('SELECT * FROM customers');
$customers = Array();
if($result->num_rows >= 1){
while($row = $result->fetch_assoc()){
$customer = new Customer($row['customerName'], $row['phoneNumber'], $row['emailAddress']);
$customers[] = $customer;
}
$result->free();
return $customers;
}
$result->free();
return false;
}
/*
* This is an example of how to use a prepared statement
* with a select query.
*/
public function getCustomer($customerName){
$query = 'SELECT * FROM customers WHERE customerName = ?';
$stmt = $this->mysqli->prepare($query);
$stmt->bind_param('s', $customerName);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1){
$temp = $result->fetch_assoc();
$customer = new Customer($temp['customerName'], $temp['phoneNumber'], $temp['emailAddress']);
$result->free();
return $customer;
}
$result->free();
return false;
}
public function addCustomer($customer){
if(!$this->mysqli->connect_errno){
$query = 'INSERT INTO customers VALUES (?,?,?)';
$stmt = $this->mysqli->prepare($query);
$stmt->bind_param('sss',
$customer->getCustomerName(),
$customer->getPhoneNumber(),
$customer->getEmailAddress());
$stmt->execute();
if($stmt->error){
return $stmt->error;
} else {
return $customer->getCustomerName() . ' added successfully!';
}
} else {
return 'Could not connect to Database.';
}
}
}
?>
Let me know if you need any more code snippets.
Any suggestions would be very much appreciated!
mysqli::prepare returns false if there was an error.
false is not an object, thus you get the error:
call to method function on bind_param() on a non-object.
You can get the error message by examining the $mysqli->error property.
public function addCustomer($customer) {
if(!$this->mysqli->connect_errno) {
$query = 'INSERT INTO customers (customerName,phoneNumber,emailAddress)
VALUES (?,?,?)';
$stmt = $this->mysqli->prepare($query);
if (!$stmt) {
$err = $this->mysqli->error;
echo $err;
// do something with $err
return $err;
}
$stmt->bind_param('sss',
$customer->getCustomerName(),
$customer->getPhoneNumber(),
$customer->getEmailAddress());
if(!$stmt->execute()){
return $stmt->error;
} else {
return $customer->getCustomerName() . ' added successfully!';
}
} else {
return 'Could not connect to Database.';
}
}
The most typical reason why prepare fails is a malformed or invalid query, but without knowing the customer schema or constraints I can't be sure what your particular problem is.