How do I dynamically define an index using an existing select query? - php

I am trying to use IsNull() to return the current variable value, but I receive an undefined Index error. The issue is that the query returns a full array.
How do I go about assigning a specific memberID so IsNull() will return the information already in the DB back into the query, thus stopping the query from erasing my current field data.
if(!empty($_POST)) {
switch (true) {
//Removed other case for brevity
case isset($_POST['update']):
if($_POST['name'] != "") {
$name = trim($_POST['name']);
}
else {
$name = NULL;
}
if($_POST['designation'] != "") {
$designation = trim($_POST['designation']);
}
else {
$designation = NULL;
}
if($_POST['rank'] != "") {
$rank = trim($_POST['rank']);
}
else {
$rank = NULL;
}
if($_POST['currentScore'] != "") {
$currentScore = trim($_POST['currentScore']);
}
else {
$currentScore = NULL;
}
if(!is_null($name) || !is_null($designation) || !is_null($rank) || !is_null($currentScore)) {
$update = $conn->prepare("UPDATE members SET name = IsNull(?, name), designation = IsNull(?, designation), rank = IsNull(?, rank), currentScore = IsNull(?, currentScore) WHERE memberID = ? ");//Prepared statements are immune to sql injection, so they are used for security
$update->bind_param('ssiii', $name, $designation, $rank, $currentScore, $memberID);// Binding the values to use in the prepared statement
if($update->execute()) {
header('location: index.php');
die();
}
}
break;
// case isset($_POST['delete']):
// // Delete statement goes here
// break;
}
}
if($results = $conn->query("SELECT *, ((previousScore + currentScore) / 2) AS avgScore FROM members")) {
FROM members")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row; //Appending value to array
}
$results->free();
}
}

Related

Lead Save Database Error In SuiteCRM

I've created a Logic Hook within the Leads module to save to a field in the database. The problem is that when I save the Lead first it displays a duplicate message:
Database failure error check SuiteCRM logs.
If I comment out this code the Lead is then saved.
LogicHook:
<?php
class LeadData
{
public function leadSaveData(&$bean, $events, $arguments)
{
$stateId = $bean->state_c;
if ($stateId != "") {
$beanst_state = BeanFactory::getBean('s1_state', $stateId);
$StateName = $beanst_state->name;
$bean->resstate_c = $StateName;
} else {
$bean->resstate_c = "Punjab";
}
if (!empty($bean->mediatype_c)) {
$mediaType = $bean->mediatype_c;
$callstatus = $bean->callstatus_c; //for follow up
if ($mediaType == 'Selectmedia' && $mediaType != '') {
$bean->refrence_c = 'null';
} else if ($mediaType == 'Refrence') {
$bean->eventname_c = 'null';
} else {
$bean->mediatype_c = 'null';
$bean->refrence_c = 'null';
$bean->eventname_c = 'null';
}
if ($callstatus != 'followup') {
$bean->calllater_c = '0000-00-00 00:00:00';
}
$bean->save();
}
}
}
Please follow these steps in your code to make this error correct or working. Hope so it will helps you.
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if (!defined('sugarEntry') || !sugarEntry)
die('Not A Valid Entry Point');
class saveextradata_logic_hooks_class
{
static $already_ran = false;
function saveextradata_after_save_method(&$bean, $events, $arguments)
{
global $db;
if (self::$already_ran == true) return;
self::$already_ran = true;
$lead_id = $bean->id;
$stateId = $_POST['state_c'];
$sql = "select name from s1_state where id='$stateId'";
$query = $db->query($sql);
$result = $db->fetchByAssoc($query);
$statename = $result[name];
if ($stateId != "") {
$statename;
} else {
$statename = "Punjab";
}
if (!empty($_POST['mediatype_c'])) {
$mediaType = $_POST['mediatype_c'];
if ($mediaType == 'Selectmedia' && $mediaType != '') {
$mediatype = 'Selectmedia';
$reference = 'null';
$eventname = $_POST['eventname_c'];
} else if ($mediaType == 'Refrence') {
$mediatype = 'Refrence';
$reference = $_POST['refrence_c'];
$eventname = 'null';
} else {
$mediatype = 'null';
$reference = 'null';
$eventname = 'null';
}
}
$callstatus = $_POST['callstatus_c'];//for follow up
if ($callstatus != 'followup') {
$calllater = '0000-00-00 00:00:00';
}
/*$bean->eventname_c = $eventname;
$bean->refrence_c = $reference;
$bean->mediatype_c = $mediatype_c;
$bean->calllater_c = $calllater;
$bean->resstate_c = $statename;
$bean->save();*/
$leadupdate = "update leads_cstm set resstate_c='$statename',eventname_c='$eventname',refrence_c='$reference',mediatype_c='$mediatype',calllater_c='$calllater' WHERE id_c = '$lead_id'";
$resultProductmasterdetail = $db->query($leadupdate);
}
}

Prevent duplicate value in database in Doctrine 1.2

I have a filling form that's work fine.Until recently a user complained of duplicate values being saved in database.Table Lts is related to table2 Koleks in a one to many relationship
action
public function executeKolect(sfWebRequest $r){
$areaId = //code;
$this->lts = Doctrine_Core::getTable('Lts')->getPaid($areaId, $this->selectedLot);
if($r->isMethod('post')) {
//code
}
foreach($this->lts as $l) {
$amount = $r->getParameter('amount_received_'.$l['id']);
$dateOfPayment = $r->getParameter('date_of_payment_'.$l['id'], date('Y-m-d'));
$startPayment = $l['date_start_of_payment'];//date_of_payment should not less than date_start_of_payment
$collectionsTable = Doctrine_Core::getTable('Koleks')->getDateCreate($l['id'],$dateOfPayment);
//here i want to make a method to check if the date_of_payment value that i want to insert does not exist yet in the Koleks table related to Lts table
$koleksTable = Doctrine_Core::getTable('Koleks')->getDateCreate($l['id'],$dateOfPayment);
if ($koleksTable >0) {
$this->fieldErrors['date_of_payment_'.$l['id']] = 'exist';
}
else {
//code ..proceed
}
}
now in doctrine table
public function getDateCreate($loanId,$datePayment) {
$q = $this->createQuery('k')
//->select('k.date_created')
// ->from('Koleks k')
->innerJoin('k.Lts l')
->where('k.l_id=?',$loanId)
->andWhere('k.date_created=?',$datePayment);
//return $q->count();
$dateCreate = $q->count();
if ($dateCreate == 1) {
$res = $q->fetchAll();
return $res;
}
else {
return $dateCreate;
}
}
I want to return an error if a same 'date_created' value is already exist in a Koleks table
But this code will not work..
In my previous project,Using mysqli, I can easily 'avoid' duplicates by using this code
//Action
$collectionsTable=$link->getdateCreated($date,$id)
if $collectionsTable > 0 {
echo "cant proceed"
}
else {
//code to proceed
}
//in myclass.php
$date = _POST//
function getDateCreate($date) {
$query = $this->link->query("SELECT date_created FROM Koleks WHERE date_created = '$date'");
$rowcount = $query->rowCount();
if($rowcount == 1)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowcount;
}
}
I think your code in the Doctrine Table should be (double check the aliases)
public function getDateCreate($loanId,$datePayment) {
$q = $this->createQuery('k')
->innerJoin('k.Lts l')
->andWhere('k.l_id = ?',$loanId)
->andWhere('k.date_created = ?',$datePayment);
return $q;
}
and in your action
//[...]
$koleksTable = Doctrine_Core::getTable('Koleks')->getDateCreate($l['id'],$dateOfPayment);//GET THE QUERY
$koleksTable->execute(); //EXECUTE THE QUERY
if ($koleksTable->count() >0) {
$this->fieldErrors['date_of_payment_'.$l['id']] = 'exists';
}
else
{
//code ..proceed
}

Combination of field search using PHP & MYSQL

I am working on an assignment using PHP & MYSQL.
one of the tasks is to search on any combination of the fields. That includes Dropdown boxes populated from the Database. and Text fields.
t2ath contains
ID
SPORT
COUNTRY
GENDER
FIRSTNAME
LASTNAME
Image
I've been working on this code for a week to be able to search on any combination with no errors.
I am wondering if there is another more efficient way to do it.
$selectedSport = $_POST['sport']; $gender =$_POST['gender']; $fName =$_POST['fname']; $lName =$_POST['lname']; $country =$_POST['country'];
$sql_fName=""; $sql_lName=""; $sql_gender=""; $sql_sport=""; $sql_country="";
$checkFiled=False;
$where="";
$and="";
//
if ( $selectedSport=="showAll")
{
!isset($selectedSport);
}
else
{
if (isset($selectedSport))
{
if ($checkFiled==True)
{
$sql_sport = " AND t2ath.sport = '$selectedSport'" ;
}
else
{
$sql_sport = " t2ath.sport = '$selectedSport' " ;
$checkFiled=True;
}
}
else {
$sql_sport = "";
}
}
//
if ( $country =="showAll")
{
!isset($country);
}
else
{
if (isset($country))
{
if ($checkFiled ==True)
{
$sql_country = " AND t2ath.country = '$country'" ;
}
else
{
$sql_country = " t2ath.country = '$country' " ;
$checkFiled=True;
}
}
else {
$sql_country = "";
}
}
//
if ( $gender=="Gender")
{
!isset($gender);
}
else
{
if (isset($gender))
{
if ($checkFiled ==True)
{
$sql_gender = " AND t2ath.gender = '$gender'" ;
}
else
{
$sql_gender = " t2ath.gender = '$gender' " ;
$checkFiled=True;
}
}
else {
$sql_gender = "";
}
}
//
if ($fName =="")
{
!isset($fName);
}
else
{
if (isset($fName))
{
if ($checkFiled==True)
{
$sql_fName = " AND t2ath.firstName = '$fName'" ;
}
else
{
$sql_fName = " t2ath.firstName = '$fName' " ;
$checkFiled=True;
}
}
else {
$sql_fName = "";
}
}
//
if ($lName =="")
{
!isset($lName);
}
else
{
if (isset($lName))
{
if ($checkFiled==True)
{
$sql_lName = " AND t2ath.lastName = '$lName' " ;
}
else
{
$sql_lName = " t2ath.lastName = '$lName' " ;
$checkFiled=True;
}
}
else
{
$sql_lName = "";
}
}
if ($checkFiled == True)
$where=" where ";
$selectString = "SELECT t2ath.lastName,t2ath.firstName,t2ath.image,t2ath.sport,t2ath.gender,t2ath.country,t2country.flag FROM t2ath LEFT JOIN t2country
ON t2ath.country = t2country.name $where $sql_sport $sql_country $sql_gender $sql_fName $sql_lName ";
$result = mysql_query($selectString);
Instead of all those conditionals about whether to add AND when concatenating to the query, use an array and implode.
$fields = array('sport' => 'sport',
'gender' => 'gender',
'fname' => 'firstName',
'lname' => 'lastName',
'country' => 'country');
$wheres = array();
foreach ($fields as $postfield => $dbfield) {
if ($_POST[$postfield] != 'showAll') {
$wheres[] = "$dbfield = '" . mysql_real_escape_string($_POST[$postfield]) . "'";
}
}
$selectString = "SELECT t2ath.lastName, t2ath.firstName, t2ath.image, t2ath.sport, t2ath.gender, t2ath.country, t2country.flag
FROM t2ath LEFT JOIN t2country
ON t2ath.country = t2country.name";
if (count($wheres) > 0) {
$selectString .= " WHERE " . implode(" AND ", $wheres);
}
$result = mysql_query($selectString);
To see how to do it similarly using PDO prepared statements, see my answer here: What code approach would let users apply three optional variables in PHP/MySQL?
I've done something similar in the past where I checked the value from different fields and then added them to a series of arrays. I created an array for select, from, where, order. You can do similar for other sets like group or limit. Then I ran 'array_unique', imploded them and put them into the SQL string.
$array_select = array('users.Id'); // SET SOME DEFAULTS SO THE QUERY WILL ALWAYS RUN
$array_from = array('users');
$array_where = array();
$array_order = array();
if (isset($first_name)) {
$array_select[] = 'First_Name';
$array_from[] = 'users';
}
if (isset($city)) {
$array_select[] = 'City';
$array_from[] = 'user_contact';
$array_where[] = 'users.Id = user_contact.City';
}
if ($array_select) {
$array_select = array_unique($array_select);
$string_select = implode(', ', $array_select);
}
if ($array_where) {
$array_where = array_unique($array_where);
$string_where = 'WHERE '.implode(' AND ', $array_where);
}
// REPEAT FOR OTHERS ...
// BUILD THE QUERY OUT
$sql = 'SELECT '.$string_select.' FROM '.$string_from.' '.$string_where.' ...
Why not evaluate your string with each column (this is a guide only, I'm not building your PHP code there:
SELECT
*
FROM
table
WHERE
(ID = $id OR $id = 'showAll')
AND (SPORT = $sport OR $sport = 'showAll')
AND (COUNTRY = $country OR $country = 'showAll')
AND (GENDER = $gender OR $gender = 'showAll')
AND (FIRSTNAME = $firstname OR $firstname = 'showAll')
Just need to make sure you NVL the variables to an appropriate value (whether it be int or string)

Redirect to page if data is missing

OK so I have been working far too long today and I am stuck on something simple (I think)
function commonData($uid)
{
if ($uid)
{
$sql = "
SELECT a.user_id, a.email, a.username, a.displayname, a.level_id, a.photo_id
FROM engine4_users AS a
WHERE a.user_id = ".$uid;
}
$UserInfo = #mysql_fetch_assoc(mysql_query($sql));
if ($UserInfo[user_id])
{
if ($UserInfo[photo_id] && $UserInfo[photo_id]!="NULL")
{
$PPhoto = #mysql_fetch_assoc(mysql_query("SELECT a.* FROM engine4_storage_files AS a WHERE a.file_id = ".$UserInfo[photo_id]));
$photo = SITE.$PPhoto[storage_path];
}
else $photo = NO_PHOTO;
$queryMoreProfile = mysql_query("SELECT * FROM engine4_user_fields_values AS a WHERE a.item_id = ".$UserInfo[user_id]);
while ($moreProfile = #mysql_fetch_assoc($queryMoreProfile))
{
//$location = '';
if ($moreProfile['field_id']==24)
{
$locationNumber = $moreProfile['value'];
$locationsql = #mysql_fetch_assoc(mysql_query("SELECT a.* FROM engine4_user_fields_options AS a WHERE a.option_id = ".$locationNumber));
if (isset($locationsql['label']) && !empty($locationsql['label']))
{
$location = $locationsql['label'];
}
}
//if(empty($location))
//{
// header("Location: http://www.fetishmen.net/members/edit/profile");
// exit;
//}
}
What I am TRYING to do is say, IF $location has no value (missing out of the database completely) redirect to a page. What am I doing wrong here?
The indexes of the array $moreProfile and $locationsql need to be either a variable or a string,
if ($moreProfile['field_id']==24) //or $field_id
{
$locationNumber = $moreProfile['value']; //or $value
$locationsql = #mysql_fetch_assoc(mysql_query("SELECT a.* FROM engine4_user_fields_options AS a WHERE a.option_id = ".$locationNumber));
$location = $locationsql['label']; //or $label
}
if(empty($location))
{
header("Location: http://website.com");
exit;
}
Edit: As per OP's comments,
if ($moreProfile['field_id'] == 24 )
{
$locationNumber = $moreProfile['value']; //or $value
$locationsql = #mysql_fetch_assoc(mysql_query("SELECT a.* FROM engine4_user_fields_options AS a WHERE a.option_id = ".$locationNumber));
$location = $locationsql['label']; //or $label
} else if(empty($moreProfile['field_id'])) {
header("Location: http://website.com");
exit;
}
You should stop using # and put in place proper checking that mysql_result and mysql_fetch_assoc is returning something. Try this and see if it redirects for you:
$location = '';
if ($moreProfile['field_id']==24)
{
$locationNumber = $moreProfile['value'];
$locationsql = #mysql_fetch_assoc(mysql_query("SELECT a.* FROM engine4_user_fields_options AS a WHERE a.option_id = ".$locationNumber));
if (isset($locationsql['label']) && !empty($locationsql['label'])) {
$location = $locationsql['label'];
}
}
if(empty($location))
{
header("Location: http://website.com");
exit;
}

both if and else statements excecuting

I've got a weird problem: both my if and else statements are executing. Here's my code:
if ($sel_user['name'] != $name) {
$query = "UPDATE owner SET
..."
$result = mysql_query($query);
if (mysql_affected_rows() ==1) {
$query2 = "UPDATE queue_acl SET
..."
$result2 = mysql_query($query2);
if (mysql_affected_rows() ==1) {
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
}
}
if ($sel_user['orgId'] != $orgId) {
$query = "UPDATE ownerOrganization SET
..."
$result = mysql_query($query);
if (mysql_affected_rows() ==1) {
$query2 = "UPDATE queue_acl SET
..."
$result2 = mysql_query($query2);
if (mysql_affected_rows() ==1) {
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
}
}
if ($sel_user['date_expires'] != $colVal[0] ||
$sel_user['admin'] != $colVal[4]) {
$query3 = "UPDATE queue_acl SET
..."
$result3 = mysql_query($query3);
if (mysql_affected_rows() ==1){
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
} else {
$_SESSION['updates_occurred'] = false;
$message = "<i>There were no edits to apply</i>";
}
When I run this, the queries are being sent and everything is being updated fine, but the "There were no edits" message is also being printed
Anyone know why?
EDIT: I do not want to use elseif statements; the events are not mutually exclusive. That is, if $sel_user['name'] != $name AND $sel_user['orgId'] != $orgId, it is required that both queries are sent
If you don't want to wrap everything in an if/else if statements, one could set a flag at the end of each if check.
if($sel_user['name'] != $name) {
// CODE HERE
$flag = true;
}
if(!$flag){
$message = "<i>There were no edits to apply</i>";
}
It's that or you can run the if check off $_SESSION['updates_occurred']
Instead of doing lots of ifs, you should be doing elseifs
i.e.
if () {
} elseif () {
} else {
}
hope that helps.
if(!printf("Hello")) {
echo "Hello";
}
else {
echo " World";
}

Categories