Existing record in php - php

Whenever I add a new place/description in my UI, it will save automatically to my database. My problem is that I can still add a place eventhough it's already existing. All I want is that it won't save/update a new description/place if it's already exist.
Any advice would be much appreciated.
Thanks.
This is my my EditPlaces:
public function executeEditPlaces(sfWebRequest $request)
{
try{
$id = pg_escape_string(strip_tags($request->getParameter("id")));
// $id = $request->getParameter("id");
$query = "select description from country.regions where id = ('$id')";
// die($query);
$result=$this->conn->fetchAll($query);
if(count($result)>0){
$v = $result[0];
$data['data'] = array('description' => $this->formatString($v['description']));
}
$data['success']=true;
$data['msg']=$msg;
die(json_encode($data));
}
catch(exception $e)
{
$data['success']=false;
$data['msg']=$e->getMessage();
die(json_encode($data));
}
}
This is my UpdatePlaces:
public function executeUpdatePlaces(sfWebRequest $request)
{
try{
$by = $_SESSION['employee_id'];
$now = date("Y-m-d H:I:s");
$id = $request->getParameter("id");
$description = pg_escape_string(strip_tags($request->getParameter("description")));
$description = trim($description);
if(strlen($description) == 0)
{
die('cannot be empty');
}
else
{
$query = "update country.regions set description=('$description'),modified_by=('$by'),date_modified=('$now') where id=('$id')";
$msg = "Existing Region Successfully Updated.";
$this->conn->execute($query);
$data['success']=true;
$data['msg']=$msg;
die(json_encode($data));
}
}
catch(exception $e)
{
$data['success']=false;
$data['msg']=$e->getMessage();
die(json_encode($data));
}
}

There is two way:
You can alter your table so the column is unique
ALTER IGNORE TABLE country.regions ADD UNIQUE (description);
Check if your description/place already exist using a select
$query = "select description from country.regions";
$result=$this->conn->fetchAll($query);
if(count($result)>0){
print 'already exist'
} else {
//insert code
}

Please check if $description of duplicated entries are really the same.
You may introduce UNIQUE constraint to SQL schema for the columns that must be unique - it will introduce security in the lower layer.
Please check if description is of type bytea. If yes, pg_escape_bytea should be used instead of pg_escape_string.

Related

Move MySQL table row to another table using PDO

i tried to follow this mysql - move rows from one table to another with action to perform a "move to archive" function using PDO and i am failing miserably.
So i have created a job card system, and to cut it short, when a job is complete, i have a "ARCHIVE" button that essentially needs to move the selected job card from table "repairs" into table "archived_repairs". The 2 tables are exactly the same, it just needs to be deleted from repairs table and moved to archived_repairs table in case we need to come back to it at a later stage.
This is the button/link i am using on my CRUD table:
<td>Archive</td>
The above is fine and dandy and goes to a page i named "archive_repair.php" with the following php code:
<?php
require_once "connection.php";
if (isset($_REQUEST['archive_id']))
{
try
{
$job_number = $_REQUEST['archive_id'];
$select_stmt = $db->prepare('SELECT * FROM repairs WHERE job_number =:job_number');
$select_stmt->bindParam(':job_number', $job_number);
$select_stmt->execute();
$row = $select_stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}
catch(PDOException $e)
{
$e->getMessage();
}
}
if (isset($_REQUEST['btn_archive']))
{
$job_number = $_REQUEST['job_number'];
$date = $_REQUEST['date'];
$client_full_name = $_REQUEST['client_full_name'];
$client_email = $_REQUEST['client_email'];
$client_phone = $_REQUEST['client_phone'];
$item_for_repair = $_REQUEST['item_for_repair'];
$repair_description = $_REQUEST['repair_description'];
$hardware_details = $_REQUEST['hardware_details'];
$diagnostic_fee = $_REQUEST['diagnostic_fee'];
$tech_assigned = $_REQUEST['tech_assigned'];
$current_status = $_REQUEST['current_status'];
$technician_notes = $_REQUEST['technician_notes'];
$admin_notes = $_REQUEST['admin_notes'];
$invoice_status = $_REQUEST['invoice_status'];
$invoice_number = $_REQUEST['invoice_number'];
if (empty($invoice_status))
{
$errorMsg = "Please change Invoice Status Before Archiving this Job Card";
}
else if (empty($invoice_number))
{
$errorMsg = "Please Enter a SAGE Invoice Reference Before Archiving this Job Card";
}
else
{
try
{
if (!isset($errorMsg))
{
$archive_stmt = $db->prepare('INSERT INTO archived_repairs job_number=:job_number, date=:date, client_full_name=:client_full_name, client_email=:client_email, client_phone=:client_phone, item_for_repair=:item_for_repair, repair_description=:repair_description, hardware_details=:hardware_details, diagnostic_fee=:diagnostic_fee, tech_assigned=:tech_assigned, current_status=:current_status, technician_notes=:technician_notes, admin_notes=:admin_notes, invoice_status=:invoice_status, invoice_number=:invoice_number');
$archive_stmt->bindParam(':job_number', $job_number);
$archive_stmt->bindParam(':date', $date);
$archive_stmt->bindParam(':client_full_name', $client_full_name);
$archive_stmt->bindParam(':client_email', $client_email);
$archive_stmt->bindParam(':client_phone', $client_phone);
$archive_stmt->bindParam(':item_for_repair', $item_for_repair);
$archive_stmt->bindParam(':repair_description', $repair_description);
$archive_stmt->bindParam(':hardware_details', $hardware_details);
$archive_stmt->bindParam(':diagnostic_fee', $diagnostic_fee);
$archive_stmt->bindParam(':tech_assigned', $tech_assigned);
$archive_stmt->bindParam(':current_status', $current_status);
$archive_stmt->bindParam(':technician_notes', $technician_notes);
$archive_stmt->bindParam(':admin_notes', $admin_notes);
$archive_stmt->bindParam(':invoice_status', $invoice_status);
$archive_stmt->bindParam(':invoice_number', $invoice_number);
if ($archive_stmt->execute())
{
$delete_stmt = $db->prepare('DELETE FROM repairs WHERE job_number =:job_number');
$delete_stmt->bindParam(':job_number', $job_number);
$delete_stmt->execute();
header("refresh:1;repairs.php");
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>
This is my connection.php file:
<?php
$db_host="localhost"; //localhost server
$db_user="ecemscoz_ecemsapp"; //database username
$db_password="C3m3t3ry!#"; //database password
$db_name="ecemscoz_ecemsapp"; //database name
try
{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>
When i click on the ARCHIVE button/link, the page is just blank (white screen), no errors show, nothing is moved to the other database and nothing is deleted. Ive only been coding PHP since 2020 so still new at this, but from my understanding this should of worked... Am i missing something in my code that i am not seeing?
You'll have a much easier time doing this directly in MySQL.
Something like the following should be essentially all you need.
$archive_stmt = $db->prepare("INSERT INTO archived_repairs (
job_number,
date,
client_full_name,
client_email,
client_phone,
item_for_repair,
repair_description,
hardware_details,
diagnostic_fee,
tech_assigned,
current_status,
technician_notes,
admin_notes,
invoice_status,
invoice_number
) (
SELECT
job_number,
date,
client_full_name,
client_email,
client_phone,
item_for_repair,
repair_description,
hardware_details,
diagnostic_fee,
tech_assigned,
current_status,
technician_notes,
admin_notes,
invoice_status,
invoice_number
FROM
repairs
WHERE
job_number =:job_number )");
$archive_stmt->bindParam(':job_number', $job_number);
if ($archive_stmt->execute())
{
$delete_stmt = $db->prepare('DELETE FROM repairs WHERE job_number =:job_number');
$delete_stmt->bindParam(':job_number', $job_number);
$delete_stmt->execute();
header("refresh:1;repairs.php");
}

PHP verify in db if exist duplicate

I have this function:
public function addToFavoriteList($eventId, $userId)
{
$sql = "INSERT INTO favorites (eventi_id, user_id) VALUES ($eventId, $userId)";
$resultSet = $this->db->execute($sql);
if (!$resultSet) {
return array('error' => 'event exsist in favorites');
}
return array('error' => '');
}
and i want to check if the event alredy exist in db so i can show and error message for the user.
I write something like that but it doesen't work.
if (isset($_POST['addToFavourite'])) {
$eventId = htmlspecialchars(trim($_POST['id']));
$addToFavoriteOutcome = $eventMgr->addToFavoriteList($eventId, $userId);
if (isset($addToFavoriteOutcome)) {
$errorMessage = $addToFavoriteOutcome['error'];
}
}
Try changing this:
if (isset($addToFavoriteOutcome)) {
$errorMessage = $addToFavoriteOutcome['error'];
}
to this
if ($addToFavoriteOutcome) {
$errorMessage = $addToFavoriteOutcome['error'];
}

proper way to check if input "promo code" matches with a database column

I would like to ask, what will be the best way to code using SQL and PHP, on how to check if the input in a textfield matches with a value in an SQL column?
I only have three values in the table. my targets are:
retrieve (POST) the value of the input
check the whole column to see if any matches the "promo code" typed
the "tinyint" used value will turn to 1
echo or affect other database tables if conditions are met
pseudocode will be alright, I would just like the proper procedure.
UPDATE: I tried the solution from #Bitwise Creative, im not getting an echo to appear, which part did i do wrong? also, i got my db where the table is located using a variable.
<form method="get">
<input type="text" name="lux_code" placeholder="ENTER PROMO CODE" style="text-align:center;">
<input type="submit" class="full_width btn color-white mwc-orange-background-color" name="redeem" value="REDEEM">
</form>
<?php
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
if (isset($_POST['redeem']) && $_POST['redeem'] == 'REDEEM'){
if (isset($_POST['lux_code']) && $_POST['lux_code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM promocode_3 WHERE coupon_code = ? AND used = ?', array($_POST['lux_code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE promocode_3 SET used = ? WHERE coupon_code = ?', array(1, $_POST['lux_code']));
// Additional handling...
echo 'Code accepted!';
}
}
}
?>
Assuming coupon_code has a unique index... Something like:
<?php
if (isset($_POST['code']) && $_POST['code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM coupons WHERE coupon_code = ? AND used = ?', array($_POST['code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE coupons SET used = ? WHERE coupon_code = ?', array(1, $_POST['code']));
// Additional handling...
echo 'Code accepted!';
}
}
You can do like this-
$couponcode = $_POST['coupon'];
$sql = "update table_name set used = 1 where coupon_code = $couponcode && used = 0";
The best way is to retrieve all your unused coupon codes and then iterate over the collection and check if the posted value is a match.
I would write a function in my functions.php file as so:
function getCoupons() {
global $db;
try {
$stmt = $db->prepare("SELECT * FROM coupons WHERE `used` = 0");
$stmt->execute();
return $stmt->fetchall();
} catch (Exception $e) {
echo $e->getMessage();
}
}
I would then call the function and store the results into an array in my test.php file like so:
$coupons = getCoupons();
I would also need the posted value, I'll retrieve it like so:
$couponCode = $_POST['coupon'];
I would then iterate over the result set to check for a match in the same file:
$match = false;
foreach($coupons as $coupon){
if($coupon['coupon_code'] == $couponCode){ //check to see if posted value matches
$match = true;
$stmt2 = $db->prepare("UPDATE coupons SET used =
'1' WHERE p3id = :id");
$stmt2->execute(array(
':id'=>$coupon['id']
));
break;
}
}
if($match){
echo 'Coupon code exists!';
} else {
echo 'No Coupon code exists!';
}

Trying to retreive int type from function and compare it with $_Get value (mysql PHP)

I trying to retreive int type from database and compare it with $_Get value
Here is the code for when the user click on the button
if(isset($_GET['btn_placeorder']))
{
$Quantity_Ordered=(int)$_GET['Quantity_Ordered'];
**# retreivng another value from function to compare it as integer**
$number= (int)$auth_user->Blood_Bankavaliable ($Blood_BankID,$Type_Ordered);
try
{
if ($Type_Ordered=="" || $Quantity_Ordered=="")
{
$error[] = "Valid data is required!";
}
else if($Quantity_Ordered >$number) {
$error[] = "This Number is not avaliable in our Stock !";
}
Here is the code for the function
function Blood_Bankavaliable($blood_bankID,$Type_Ordered) {
global $conn;
# query for getting the value from the database
$query = "select sum(Blood_quantity) as d from Donor_Blood_Bank where Blood_Type=$Type_Ordered and blood_bankID= $blood_bankID";
try {
$statement = $this->conn->prepare($query);
$statement->execute();
$result = $statement->fetchall;
return $result;
} catch(PDOException $e)
{
echo $e->getMessage();
}
}
I don't know what is the problem with my code any help?
First, it should be $result = $statement->fetchAll();(a function or method), not $result = $statement->fetchall (a property).
Second, please read the manul, fetchall() return an array. therefore you can't cast it to int directly. run print_r( $auth_user->Blood_Bankavaliable($Blood_BankID,$Type_Ordered) ); to see yourself.

Best way to check for existing user in mySQL database? [duplicate]

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 7 months ago.
I am trying to create a user login/creation script in PHP and would like to know the best way to check if a username exists when creating a user. At the moment, I have the following code:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$this->users = $server->query("SELECT * FROM user_list");
while ($check = mysql_fetch_array($this->users) {
if ($check['uname'] == $uname) {
What I'm not sure about is the best logic for doing this. I was thinking of adding a boolean variable to do something like (after the if statement):
$boolean = true;
}
if ($boolean) {
echo "User already exists!";
}
else {
$server->query("INSERT USER INTO TABLE");
echo "User added Successfully";
}
But this seems a little inefficient - is there a more efficient way to do this? Sorry if this has a basic solution - I'm a relatively new PHP programmer.
Use the WHERE clause to get only rows with the given user name:
"SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'"
Then check if the query results in selecting any rows (either 0 or 1 row) with MySQLi_Result::num_rows:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $server->query("SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'");
if ($result->num_rows() === 0) {
if ($server->query("INSERT INTO user_list (uname) VALUES ('".$server->real_escape_string($uname)."'")) {
echo "User added Successfully";
} else {
echo "Error while adding user!";
}
} else {
echo "User already exists!";
}
}
This basically involves doing a query, usually during validation, before inserting the member into the database.
<?php
$errors = array();
$alerts = array();
if (isset($_POST['register'])) {
$pdo = new PDO('[dsn]', '[user]', '[pass]');
// first, check user name has not already been taken
$sql = "SELECT COUNT(*) AS count FROM user_list WHERE uname = ?";
$smt = $pdo->prepare($sql);
$smt->execute(array($_POST['uname']));
$row = $smt->fetch(PDO::FETCH_ASSOC);
if (intval($row['count']) > 0) {
$errors[] = "User name " . htmlspecialchars($_POST['uname']) . " has already been taken.";
}
// continue if there are no errors
if (count($errors)==0) {
$sql = "INSERT INTO user_list ([fields]) VALUES ([values])";
$res = $pdo->exec($sql);
if ($res==1) {
$alerts[] = "Member successfully added.";
} else {
$errors[] = "There was an error adding the member.";
}
}
}
The above example uses PHP's PDO, so change the syntax to use whatever database abstraction you use.

Categories