I create a function to find all firstname and lastname in my database all I want if that data is already exist I just want to output, error message
my question is how to create a function to check if data is already exist?
this is my function to find all data of firstname and lastname.
function find_student_by_firstname($firstname){
global $con;
$safe_firstname = prep($firstname);
$sql = "SELECT * ";
$sql .= "FROM studeprofile ";
$sql .= "WHERE FirstName = '{$safe_firstname}' ";
$sql .= "LIMIT 1";
$student_set = mysqli_query($con, $sql);
confirm_query($student_set);
if($student = mysqli_fetch_assoc($student_set)){
return $student;
} else {
return null;
}
}
function find_student_by_lastname($lastname){
global $con;
$safe_lastname = prep($lastname);
$sql = "SELECT * ";
$sql .= "FROM studeprofile ";
$sql .= "WHERE LastName = '{$safe_lastname}' ";
$sql .= "LIMIT 1";
$student_set = mysqli_query($con, $sql);
confirm_query($student_set);
if($student = mysqli_fetch_assoc($student_set)){
return $student;
} else {
return null;
}
}
this is my current function to check if data is already exist.
function match_fistname_lastname($lastname, $firstname){
$student_firstname = find_student_by_firstname($lastname);
if($student_firstname){
find_student_by_lastname($lastname);
} else {
return false;
}
}
If you mean by "data is already exist" that a person is in the database that matches to firstname and lastname, you don't have to execute two queries.
Use the and in mysql like this:
function find_student($firstname, $lastname){
global $con;
$safe_firstname = prep($firstname);
$safe_lastname = prep($lastname);
$sql = "SELECT * ";
$sql .= "FROM studeprofile ";
$sql .= "WHERE FirstName = '{$safe_firstname}' and LastName = '{$safe_lastname}' ";
$sql .= "LIMIT 1";
$student_set = mysqli_query($con, $sql);
confirm_query($student_set);
if($student = mysqli_fetch_assoc($student_set)){
return $student;
} else {
return null;
}
}
Related
I want to retrieve data from three tables using some condition and then insert/update in another three tables. This is a very simple process, the script of which is developed in php. But the catch is that the records retrieved from each table is 100k+. PHP script runs only with small number of records and gives time out error for large data. Can anyone please suggest how to solve this issue. All the three tables data needs to be fetched at runtime. Below is my php script which gives timeout error
switch($action){
case 'tequipebudget':
$oldPresta = budPrestaDataTransfer::getOldPresta('tequipebudget');
$budProviderBudget = budPrestaDataTransfer::updatebudProviderBudget($oldPresta, 'budproviderbudget', 3);
break;
case 'tequipebudgetjum':
$oldPrestaJum = budPrestaDataTransfer::getOldPresta('tequipebudgetjum');
$budProviderBudgetJum = budPrestaDataTransfer::updatebudProviderBudget($oldPrestaJum, 'budproviderbudgetjum', 3);
break;
case 'tequipebudgetavhisto':
$oldPrestaAvHisto = budPrestaDataTransfer::getOldPresta('tequipebudgetavhisto');
$budProviderBudgetAvHisto = budPrestaDataTransfer::updatebudProviderBudget($oldPrestaAvHisto, 'budproviderbudgetavhisto', 3);
break;
}
static public function getOldPresta($table) {
$sql = "SELECT Annee, CodeEntite, CodeProjet, MtBudgetAEquipeKE, projet_id";
if($table == 'tequipebudgetavhisto') {
$sql .= " ,avenant_id ";
}
$sql .= " FROM ".$table." WHERE Annee < 2020 ";
$dbObj = budPDO::getInstance();
$prestaList = $dbObj->getAllResults($sql);
return $prestaList;
}
static public function updatebudProviderBudget($prestaList, $table, $autreId) {
foreach($oldPresta as $key=>$val) {
$sql = "SELECT count(*) as cnt FROM ".$table." WHERE Annee = '".$val['Annee']."' AND CodeEntite = '".$val['CodeEntite']."' AND
CodeProjet = '".$val['CodeProjet']."' AND projet_id = '".$val['projet_id']."' AND provider_id = '".$oldPresta['AuterId']."' ";
$dbObj = budPDO::getInstance();
$res = $dbObj->getOneRow($sql);
if($res['cnt'] == 0){ // record does not exists in table
$update = "INSERT INTO ".$table." SET Annee = '".$val['Annee']."', CodeEntite = '".$val['CodeEntite']."',
CodeProjet = '".$val['CodeProjet']."', cost = '".$val['MtBudgetAEquipeKE']."' ,
projet_id = '".$val['projet_id']."', provider_id = '".$autreId."',
addedon_date = '".NOW_CONST."' ";
if($table == 'budproviderbudgetavhisto') {
$update .= " ,avenant_id= '".$val['avenant_id']."' ";
}
}else {
$update = "UPDATE ".$table." SET Annee = '".$val['Annee']."', CodeEntite = '".$val['CodeEntite']."',
CodeProjet = '".$val['CodeProjet']."', cost = '".$val['MtBudgetAEquipeKE']."' ,
projet_id = '".$val['projet_id']."', provider_id = '".$autreId."',
modifiedon_date = '".NOW_CONST."' ";
if($table == 'budproviderbudgetavhisto') {
$update .= " ,avenant_id= '".$val['avenant_id']."' ";
}
$update .= " WHERE Annee = '".$val['Annee']."' AND CodeEntite = '".$val['CodeEntite']."' AND
CodeProjet = '".$val['CodeProjet']."' AND projet_id = '".$val['projet_id']."' AND provider_id = '".$autreId."' ";
if($table == 'budproviderbudgetavhisto') {
$update .= " AND avenant_id= '".$val['avenant_id']."' ";
}
}
//echo "update -- " . $update. "<br><br>";
$sth = $dbObj->pdo->prepare($update);
$exec = $sth->execute();
}
}
You could increase the timeout in your PHP settings.
ini_set('max_execution_time','{number of seconds}');
Then you will probably also have to increase the memory limit.
ini_set('memory_limit', '2GB');
But it would be better to leave large data logic to the database. So if I were you, I would write a stored procedure / function and execute it with PHP only exec
I want to check the store type in Magento and run query if the store EN else another query , I have my code below but it doesn't work:
$name = $store->getName();
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
if($name=='EN')
{
$sql= "SELECT * FROM directory_country_region_EN WHERE name='$region' ";
}
else
{
$sql = "SELECT * FROM directory_country_region_SU WHERE name='$region' "; }
Try this :
$name = Mage::app()->getStore()->getCode();
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
if($name=='EN')
{
$sql= "SELECT * FROM directory_country_region_EN WHERE name='$region' ";
}
else
{
$sql = "SELECT * FROM directory_country_region_SU WHERE name='$region' "; }
I have this function:
//get mgs by orderID
function getOrderMsgs($orderId){
global $conn;
$query = "SELECT * ";
$query .= "FROM msgs ";
$query .= "WHERE orderid=" . $orderId . " ";
$msgset = mysqli_query($conn, $query);
confirm_query($msgset);
while ($msg = mysqli_fetch_assoc($msgset)){
$return[] = $msg;
}
return $return;
}
That returns all messages with a certain message Id. Now what I need to do is check if the returned value is indeed an array since after the query we may find no messages with that specific Id which I believe won't return an array. So far this is what I have:
$msgId = sql_prep($_GET['oid']);
$order = getOrderById($msgId);
$msgs=getOrderMsgs($msgId);
echo '<h2>Order #'.$order['orderid'].': '.$order['title'].'</h2>';
echo '<h3>Message thread</h3>';
foreach($msgs as $msg){
echo $msg['msg'].'<br>'.$msg['sender'].'<br>'.$msg['timestamp'].'<br><br>';
}
And it returns an error if there is no msgs with that id in db.
To see type of a variable you can use gettype
print_r(gettype($_COOKIE));
Make sure you initialize $return before using it. This ensures you are always returning an array.
function getOrderMsgs($orderId){
global $conn;
$return = array(); // initialize variable
$query = "SELECT * ";
$query .= "FROM msgs ";
$query .= "WHERE orderid=" . $orderId . " ";
$msgset = mysqli_query($conn, $query);
confirm_query($msgset);
while ($msg = mysqli_fetch_assoc($msgset)){
$return[] = $msg;
}
return $return;
}
In you code you can then inspect the array and use the number of array elements to decide what to do next.
$order = getOrderById($msgId);
if(count($order) > 0) {
// Found something
} else {
// Nothing found
}
I have this in my functions.php file
function getUserOrders($userId){
global $conn;
$query = "SELECT * ";
$query .= "FROM orders ";
$query .= "WHERE userid=" . $userId . " ";
$odrset = mysqli_query($conn, $query);
while ($odr = mysqli_fetch_assoc($odrset)){
return $odr;
}
}
What I neeed to do in my orders.php file is display specific fields and their values from the returned $odr array as this snippet suggests
$userId = sql_prep($_SESSION['userid']) ;
getUserOrders($userId);
echo $odr['title'].$odr['orderid'].'<br>'
I am only able to do it in the functions.php file...
function getUserOrders($userId){
global $conn;
$query = "SELECT * ";
$query .= "FROM orders ";
$query .= "WHERE userid=" . $userId . " ";
$odrset = mysqli_query($conn, $query);
confirm_query($odrset);
while ($odr = mysqli_fetch_assoc($odrset)){
echo $odr['title'].$odr['orderid'].'<br>';
}
}
..and calling it in my orders.php file like so:
$userId = sql_prep($_SESSION['userid']) ;
getUserOrders();
which is not good since i need to recycle the function somewhere else and display different fields and their values. So I need to have $odr returned as an array in my order.php
Store it as an array and then return the array.
function getUserOrders($userId){
global $conn;
$query =
"SELECT *
FROM orders
WHERE userid= ?";
$odrset = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($odrset, 'i', $userId);
mysqli_stmt_execute($odrset);
while ($odr = mysqli_fetch_assoc($odrset)){
$return[] = $odr;
}
return $return;
}
I've updated your mysqli connection to use a parameterized query with prepared statement. You can read more about these here, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php. This is the preferred approach than escaping.
Later usage...
$orders = getUserOrders($_SESSION['userid']);
foreach($orders as $order) {
echo $order['title'] . $order['orderid'];
}
You may not need the sql_prep function with this approach, I'm not sure what that did. Your questions code didn't pass the userid to the function so I don't think that was your exact usage.
mysqli_fetch_assoc only returns one record at a time so you need to store the results inside an array and return the array from the function:
// functions.php
function getUserOrders($userId){
global $conn;
$query = "SELECT * ";
$query .= "FROM orders ";
$query .= "WHERE userid=" . $userId . " ";
$odrset = mysqli_query($conn, $query);
$results = array();
while ($odr = mysqli_fetch_assoc($odrset)){
$results[] = $odr;
}
return $results;
}
// in your orders file
$userid = sql_prep($_SESSION['userid']);
$orders = getUserOrders($userid);
foreach ($order as $orders) {
echo $order['title']. $order['orderid'] . '<br>';
}
I have some users in the database and I can edit their names and passwords but when I try to edit the username the query fails.
Here is my code
$user->username = $db->mysql_prep($_POST["username"]);
$user->hashed_password = ($_POST["password"]);
$user->firstname = $db->mysql_prep($_POST["firstname"]);
$user->lastname = $db->mysql_prep($_POST["lastname"]);
$user_query = $user->find_user_by_username($user->username);
$user->id = $user_query["id"];
$result = $user->change_user_by_id($user);
//->id,$user->username,$user->hashed_password,$user->firstname,$user->lastname
unset($user);
My change_user_by_id method:
public function change_user_by_id($user){
global $db;
global $session;
$query = "UPDATE users SET ";
$query .= "username = '{$user->username}', ";
$query .= "first_name = '{$user->firstname}', ";
$query .= "last_name = '{$user->lastname}' ";
$query .= "WHERE id = {$user->id} ";
$query .= "LIMIT 1";
$result = mysqli_query($db->connection, $query);
$db->confirm_query($result);
if ($result && mysqli_affected_rows($db->connection) == 1) {
// Success
$session->message("User updated.");
redirect_to("list.php");
} else {
// Failure
$session->message("User update failed.");
}
}
And my find_user_by_username method:
public static function find_user_by_username($username="default"){
global $db;
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE username = '{$username}' ";
$query .= "LIMIT 1";
$user_set = mysqli_query($db->connection, $query);
$db->confirm_query($user_set);
if($user = mysqli_fetch_assoc($user_set)) {
return $user;
} else {
return null;
}
}
EDIT:
The only error I get is from confirm_query function I get the message "Database query failed" Here is the function:
public function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
EDIT 2:
Added error messages and this is what I get:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'LIMIT 1' at line 1
I figured it out it was caused by using the username to get the id, which means changing the username meant no id could be retrieved. So I changed my code and added a hidden field for id in my form.
Old code:
$user->username = $db->mysql_prep($_POST["username"]);
$user->hashed_password = ($_POST["password"]);
$user->firstname = $db->mysql_prep($_POST["firstname"]);
$user->lastname = $db->mysql_prep($_POST["lastname"]);
$user_query = $user->find_user_by_username($user->username);
$user->id = $user_query["id"];
$result = $user->change_user_by_id($user);
unset($user);
replaced by new code:
$user->username = $db->mysql_prep($_POST["username"]);
$user->hashed_password = ($_POST["password"]);
$user->first_name = $db->mysql_prep($_POST["first_name"]);
$user->last_name = $db->mysql_prep($_POST["last_name"]);
$user->id = $db->mysql_prep($_POST["id"]);
$result = $user->change_user_by_id($user);
unset($user);