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";
}
Related
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;
}
}
I have a variable $success set to $success = "Successfully Created" but the var $success has no value inside HTML.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
if (isset($_POST['okbutton'])) {
if (isset($_POST['clientuser'], $_POST['clientpass'])) {
$clientuser = $_POST['clientuser'];
$clientpass = $_POST['clientpass'];
$_SESSION['cuser'] = $clientuser;
$_SESSION['cpass'] = $clientpass;
header('Location: trialaccount.php');
die();
}
}
}
try {
if (isset($_SESSION['cuser'])) {
$stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->rowCount();
if ($checkdup == 0) {
$stmt = $conn->prepare("INSERT INTO user (user_id, user_pass, user_online, user_enable, user_start_date, user_end_date, reseller, type) VALUES (:clientuser, :clientpass,0, 1, now(), now() + interval 4 hour, :panelUSER, 'Trial')");
$stmt->bindParam(':clientuser', $_SESSION['cuser']);
$stmt->bindParam(':clientpass', $_SESSION['cpass']);
$stmt->bindParam(':panelUSER', $username);
$stmt->execute();
$success = "Trial Account Created Successfully!";
} else {
$error = "Username '" . $_SESSION['cuser'] . "' is already taken. Try to input unique username." ;
}
}
} catch (PDOException $e) {
echo "Error: Database Error";
}
Inside my HTML, I use echo!
<?php if(isset($success)){ echo $success; } ?>
var $success is returning the value on my personal smartphone,
but no value on other devices.
I dont know what is happening?
Can I use Session instead? ty
Your method does not get the total row count. Therefore, it doesn't go through (if($checkdup == 0)) to set the value for $success. You can try the code below.
Replace:
$stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->rowCount();
With:
$stmt = $conn->prepare("SELECT COUNT(*) FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->fetchColumn();
The function should return the id of the found user or return false if not found.
Currently I am using bind result and fetch to check if a user is found in an mysql table:
public function getUserIDByName($UserName) {
$uid = "";
$i=0;
if($stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?")){
$stmt->bind_param("s", $UserName);
$stmt->execute();
$stmt->bind_result($uid);
while($stmt->fetch()){
$i++;
}
$stmt->close();
}
if($i==0){
return false;
}else{
return $uid;
}
}
This works, but I assume that there is a proper way to do this without a counter in the fetch loop. I can not use get_result as mysqlnd is not available.
Simple use num_rows to check your query return result or not
function getUserIDByName($UserName) {
if ($stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?")) {
$stmt->bind_param("s", $UserName);
$stmt->execute();
$row_cnt = $stmt->num_rows;
if ($row_cnt == 1) {
$stmt->bind_result($uid);
while ($stmt->fetch()) {
return $uid;
}
} else {
return false;
}
}
}
Use this instead
public function getUserIDByName($UserName)
{
$uid = '';
$response = false;
$stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?");
$stmt->bind_param("s", $UserName);
$stmt->execute();
$stmt->bind_result($uid);
if ($stmt->fetch()) {
$response = $uid;
}
$stmt->close();
return $response;
}
EDIT: just realized you're using mysqli and not pdo. Ill leave this here if you want to use PDO in the feature I guess.
This is how I would do it. You could change rowcount() > 0 to rowcount() === 1 if you want to guarantee only 1 user is found.
public function getUserIDByName($UserName)
{
$stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name = :name");
// bind :name to the username
$stmt->bindParam(":name", $UserName);
// execute the query
$stmt->execute();
// check the rowcount
if ($stmt->rowcount() > 0) {
// fetch the results as a associative array
return $stmt->fetch(PDO::FETCH_ASSOC);
}
// return false because rowcount wasn't bigger than 0
return false;
}
I'm trying to use prepared queries, but this code isn't working, it just stucks on the first use of prepare(). Commenting the fist if() does nothing, now it stucks on the second. No connection problems/no errors, just stuck.
If I do all of this using just mysqli_query() everything works great.
function addUser($id){
/*
if ($stmt = $this->mysqli->prepare("SELECT * FROM Users WHERE ID = ?")){
if (!($stmt->bind_param("s", $id))){
return false;
}
if ($stmt->execute()) {
if ($stmt->num_rows!=0){
return false;
}
}else{
return false;
}
}else{
return false;
}*/
if ($stmt = $this->mysqli->prepare("INSERT INTO Users VALUES (?, '')")) {
if (!$stmt->bind_param("s", $id)) {
return false;
}
if (!$stmt->execute()) {
return false;
}
return true;
}
return false;
}
and about debugging, if i change the code like this
function addUser($id){
echo "1";
if ($stmt = $this->mysqli->prepare("SELECT * FROM Users WHERE ID = ?")){
echo "2";
if (!($stmt->bind_param("s", $id))){
return false;
} ...
}else{
echo "3";
} ...
I'll see only "1" on the page.
start of the class:
class db{
private $mysqli;
function __construct($ip, $login, $password, $database){
$this->mysqli = new mysqli($ip, $login, $password, $database) or die("Problem with DB connection!");
$this->mysqli->set_charset("utf8");
}
You never execute() so nothing will happen, therefore no errors will raise.
Here is how I would write it:
function addUser($id){
if ($this->mysqli->connect_errno) {
die('Connect Error: ' . $this->mysqli->connect_errno);
}
if ($stmt = $this->mysqli->prepare("INSERT INTO Users VALUES (?, '')")) {
$stmt->bind_param("s", $id);//did you mean i for type int ?
$stmt->execute();//dont forget this!!
}else{
die('Connect Error: ' . $this->mysqli->connect_errno);
}
return ($stmt->rowCount() > 0)? true : false;
}
I am attempting to write a method that checks whether a user exists and also does some validation.
This is the code so far:
public function checkUsername(){
if((strlen($_POST['register-username']) > 2) && (strlen($_POST['register-username']) < 16)){
$stmt = $this->dbh->prepare("SELECT username FROM adrenaline_junkies_uk_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['register_username'], PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount() != 0){
return TRUE;
}else{
return $this->error .= '<span style="color:red;">Username already exists.</span>';
}
}else{
return $this->error .= '<span style="color:red;">Username must be between 3 and 15 characters.</span>';
}
}
This is how Im attempting to call it:
if( isset($_POST['register-submit'])){
$error = '';
$register = new register($_POST, $dbh);
if(!$error .= $register->checkUsername()){
//continue
}else{
$error .= $register->checkUsername();
}
}
To test it I don't enter anything in the input field to get the first error to be returned and echo it out correctly on the webpage. But nothing is displaying.
Is this the correct way of doing this? Sorry I'm not very familiar with using methods in classes. I assume I'm doing something wrong in the initial if statement in the calling program and should I be running that method twice like I do?
Use Exceptions. Like:
public function checkUsername(){
if((strlen($_POST['register-username']) > 2) && (strlen($_POST['register-username']) < 16)){
$stmt = $this->dbh->prepare("SELECT username FROM adrenaline_junkies_uk_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['register_username'], PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount() != 0){
return TRUE;
}else{
throw new Exception("Username already exists.");
}
}else{
throw new Exception("Username must be between 3 and 15 characters.");
}
}
and
if( isset($_POST['register-submit'])){
$error = '';
$register = new register($_POST, $dbh);
try {
if($register->checkUsername()){
//continue
}
} catch ($e) {
$error .= '<span style="color:red;">' . $e->getMessage() . '</span>';
}
}
You can do subclassing like:
class UsernameException extends Exception {}
try {
throw new UsernameException("Your username is too awesome");
} catch (UsernameException $e) {
exit($e->getMessage());
} catch (SomeOtherException $e) {
exit("500");
} catch (Exception $e) {
exit("que?");
}