I want to send data to my database (group_id, user_id and group_name) but only the first two are getting into the database. When I var_dump $groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname); it gives me the correct group_name. What am I doing wrong?
When I replace '" . $db->conn->real_escape_string($this->Invitation_group_name) . "' with a random word it is working well..
PHP
$groupinvitation = new GroupInvitation();
if (isset($_POST["Accept"])) {
try {
$group_id = mysql_real_escape_string($_POST["group_id"]);
$groupinfo = $group->GetGroupInfoByGroupId($group_id);
$groupname = $groupinfo['group_name'];
$requestnumber = mysql_real_escape_string($_POST['acceptID']);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$feedback = "Awesome, You just added a friend!";
} catch(Exception $e) {
$feedback = $e -> getMessage();
}
}
DECLARATIONS:
class GroupInvitation
{
private $m_sGroup_invitation_group_name;
public function __set($p_sProperty, $p_vValue)
{
switch($p_sProperty)
{
case "Invitation_group_name":
$this->m_sGroup_invitation_group_name = $p_vValue;
break;
}
}
public function __get($p_sProperty)
{
switch($p_sProperty)
{
case "Invitation_group_name":
return $this->m_sGroup_invitation_group_name ;
break;
}
}
FUNCTION:
public function AddAsGroupMember($number, $group_id)
{
$db = new Db();
$insert = "INSERT INTO tblgroup_member(
group_id,
user_id,
group_name
) VALUES (
'" . $db->conn->real_escape_string($group_id) . "',
'" . $db->conn->real_escape_string($number) . "',
'" . $db->conn->real_escape_string($this->Invitation_group_name) . "'
)";
$db->conn->query($insert);
}
Try changing
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
to
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
You could be setting the property after the insert.
Related
I don't want to save duplicate name record. I want to display errors back to the user.
But it doesn't work. I don't know what I'm doing wrong.
protected function has_unique_name($value, $current_id="0") {
$sql = "SELECT * FROM photographs ";
$sql .= "WHERE caption='" . self::$database->escape_string($this->caption) . "' ";
$sql .= "AND id != '" . self::$database->escape_string($current_id) . "'";
echo $sql;
$result = self::$database->query($sql);
$products_count = $result->num_rows;
echo $products_count . "<br />" ;
$result->free();
return $products_count === 0;
}
protected function validate() {
$this->errors = [];
$value = $this->caption;
$current_id = isset($this->id) ? $this->id : '0';
if(!$this->has_unique_name($this->caption, $current_id)) {
$errors[] = "The name must be unique.";
}
return $this->errors;
}
public function create() {
$this->validate();
if(!empty($this->errors)) { return false; }
...
The function is fetching data from the database, but the issue is, it is not fetching the next row after printing the first row.
Kindly check and tell me what I'm doing wrong?
Public function Return_Config($P_name, $WW, $KPI) {
log_message('debug', 'hd');
log_message('debug', $P_name . ' ' . $WW . ' ' . $KPI);
$P_name .= '_one_voice_perf_measured';
$select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
//echo $select_query;
$query = $this->db->query($select_query);
if ($query->row() > '0') {
return $query->row()->config;
} else {
return 'Not Measured';
}
}
It is going directly to the else part. please help
This is because you are using ->row() instead use ->result(), like:
Public function Return_Config($P_name, $WW, $KPI)
{
log_message('debug', 'hd');
log_message('debug', $P_name . ' ' . $WW . ' ' . $KPI);
$P_name.= '_one_voice_perf_measured';
$select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
// echo $select_query;
$query = $this->db->query($select_query);
if (!empty($query->result()))
{
return $query->result();
}
else
{
return 'Not Measured';
}
}
More details at https://www.codeigniter.com/userguide3/database/results.html
try this
Public function Return_Config($P_name,$WW,$KPI){
log_message('debug','hd');
log_message('debug', $P_name.' '.$WW.' '.$KPI);
$P_name .= '_one_voice_perf_measured';
$select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
//echo $select_query;
$query = $this->db->query($select_query)->row_array();
if (!empty($query)){
return query['config'];
}
else{
return 'Not Measured' ;
}
}
I have zf2 model. Inside the model, there is a function to communicate with the database with transaction.
Between the transaction I'm calling a recursive function to do transaction, where I'm passing the transaction object. Without recursive function calling it's running fine, but when I'm going to call any function where some query is running, it sends false, and due to receiving false it's being rollbacked. Below are the example code:
<?php
namespace Admin\Model;
use Zend\Db\TableGateway\TableGateway;
use Exception;
class ProjectAssignTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
/**
* $empidArray = array(1, 2, 3, 5, 12, 35);
*/
public function saveProjectAssignment($project_id, $empidArray, $data) {
$connection = $this->tableGateway->getAdapter()->getDriver()->getConnection();
$connection->beginTransaction();
try {
$sqlDelete = "DELETE FROM rjs_assignproject WHERE project_id= '" . $project_id . "' ";
$connection->execute($sqlDelete);
for ($x = 0; $x < count($empidArray); $x++) {
$sqlInsert = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $empidArray[$x] . "',designation_id='" . $data['desgi_' . $empidArray[$x]] . "',comment='" . $data['comment_' . $empidArray[$x]] . "',datetime_from='" . $data['time_from' . $empidArray[$x]] . "',datetime_to='" . $data['time_to' . $empidArray[$x]] . "' ";
$resultHistory = $connection->execute($sqlInsert);
if (!$this->recursiveEntry($connection, $empidArray[$x], $project_id)) {
throw new Exception();
} else {
return true;
}
}
$connection->commit();
return true;
} catch (Exception $ex) {
$connection->rollback();
}
}
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
$sql1 = "select * from rjs_admins where admin_id in(select parent_id from rjs_admins where admin_id=$admin_id)";
$result1 = $connection->execute($sql1);
if (count($result1) > 0) {
$sql2 = "select * from rjs_assignproject where admin_id='" . $result1[0]->admin_id . "'";
$result2 = $connection->execute($sql2);
if (count($result2) < 1) {
$sql3 = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $result1[0]->admin_id . "',designation_id='" . $result1[0]->designation_id . "' ";
$connection->execute($sql3);
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
} else {
return true;
}
}
}
} catch (Exception $ex) {
return false;
}
}
}
Your method doesn't return anything after try/catch block:
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
// ...
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
} else {
return true; // We will never get here
}
} catch (Exception $ex) {
return false;
}
// return null
}
Try this:
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
$sql1 = "select * from rjs_admins where admin_id in(select parent_id from rjs_admins where admin_id=$admin_id)";
$result1 = $connection->execute($sql1);
if (count($result1) > 0) {
$sql2 = "select * from rjs_assignproject where admin_id='" . $result1[0]->admin_id . "'";
$result2 = $connection->execute($sql2);
if (count($result2) < 1) {
$sql3 = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $result1[0]->admin_id . "',designation_id='" . $result1[0]->designation_id . "' ";
$connection->execute($sql3);
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
}
}
}
} catch (Exception $ex) {
return false;
}
return true;
}
Every time I call a query with my class for select * from table where blank=blank it always comes up "NULL" on a var_dump for the results at the end of the class. I'm still stuck on this and don't know why it's doing it, but it sends no responses for sure, because I'm getting nothing back.
mysqli.class.php
<?php
class DATABASE
{
//set up variables only for this class
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $connection;
private $paramaters = array();
private $results = array();
private $numrows;
//call connection on call of class
public function __construct($db_host, $db_user, $db_pass, $db_name)
{
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name) or die('There was a problem connecting to the database! Error #: '. $this->mysqli->connect_errno);
}
//close mysqli connection on class close
public function __destruct()
{
$this->mysqli->close();
}
//query
public function select($fields, $table, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal, $sets, $setVal)
{
switch($type)
{
case "regular":
if ($where == null)
{
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = "";
} else {
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
case "update":
if ($where == null)
{
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal;
} else {
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal . " WHERE " . $where . " = ?";
}
break;
case "insert":
if ($sets == null)
{
$queryPre = "INSERT INTO " . $table;
$querySuff = " VALUES(" . setVal . ")";
} else {
$queryPre = "INSERT INTO " . $table . " (" . $sets . ")";
$querySuff = " VALUES(" . setVal . ")";
}
case "delete":
if ($where == null)
{
$queryPre = "DELETE FROM " . $table;
$querySuff = "";
} else {
$queryPre = "DELETE FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
}
//$sql = $queryPre . "" . $querySuff;
//var_dump($sql);
//exit;
$stmt = $this->mysqli->prepare($queryPre . "" . $querySuff) or die('There was a problem preparing the Query! Error#: '. $this->mysqli->errno);
if ($whereVal == null)
{
$stmt = $this->bindVars($stmt,$setVal);
} else {
$stmt = $this->bindVars($stmt,$whereVal);
}
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
{
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch())
{
$x = array();
foreach($row as $key => $val)
{
$x[$key] = $val;
}
$results[] = $x;
}
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
}
private function bindVars($stmt,$params)
{
if ($params != null)
{
$types = '';
//initial sting with types
if (is_array($params))
{
foreach($params as $param)
{
//for each element, determine type and add
if(is_int($param))
{
$types .= 'i'; //integer
} elseif (is_float($param))
{
$types .= 'd'; //double
} elseif (is_string($param))
{
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
} else {
if (is_int($params))
{
$types = 'i';
} elseif (is_float($params))
{
$types = 'd';
} elseif (is_string($params))
{
$types = 's';
} else {
$types = 'b';
}
}
$bind_names[] = $types;
if (is_array($params))
{
//go through incoming params and added em to array
for ($i=0; $i<count($params);$i++)
{
//give them an arbitrary name
$bind_name = 'bind' . $i;
//add the parameter to the variable variable
$$bind_name = $params[$i];
//now associate the variable as an element in an array
$bind_names[] = &$$bind_name;
}
} else {
$int0 = 0;
$bind_name = 'bind' . $int0;
$$bind_name = $params;
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
return $stmt; //return the bound statement
}
}
?>
example to call and check fields - process_availability.php:
<?php
//require necessary files
require('../config/dbconfig.php');
include('../classes/mysqli.class.php');
//initiate connection
$mysqli = new DATABASE($db_host,$db_user,$db_pass,$db_name);
//take type of check
$checktype = $_POST['type'];
//check the user name
if ($checktype == "username") {
//change post to variable
$username = $_POST['username'];
//check if user name is empty
if ($username == "") {
$validuser = array("empty", "false");
echo implode(',', $validuser);
exit;
}
//if user name is more characters than 30
if (strlen($username) > 30) {
$validuser = array("max", "false");
echo implode(',', $validuser);
exit;
}
//search for same user name in database
$resultsU = $mysqli->select('*','users','username',$username,'regular',null,null,null,null,null);
//var_dump($resultsU);
if (is_array($resultsU))
{
var_dump($resultsU);
foreach($resultsU as $rowU)
{
//return results
if($rowU['username'] == "" || $rowU['username'] == NULL)
{
//user name is blank
$validuser = array("yes", "true");
echo implode(',', $validuser);
exit;
}
else {
//username is not blank, so it's taken
$validuser = array("no", "false");
echo implode(',', $validuser);
exit;
}
}
}
}
And just to show what I'm actually doing with the information, here is a PART of the java (just handles username mostly, there is a ton more for email, ect not included):
fiddle
And, of coarse, the link to the page: page link
I've been fixing other things on here, and on a technicality it works. I get a response if there IS something in the database that matches the username i type, but if there is no match, for some reason it doesn't respond at all.....
Specifically...right at the bottom of the 2nd to last function in the class:
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
When you are returning no results to the client, you need to indicate to the client that this is what you have done, and the code shown above simply outputs nothing in this case. While it is easily possible to handle this empty response correctly on the client side a better solution would be to do one of the following:
If you need the data from the result, json_encode() the results before sending them back to the client. This would mean that if the were no results you would return an empty array, but it would still be valid JSON and crucially you can easily check whether the result array is empty on the client side using result.length.
If you don't actually need the result data and all you need is to determine whether there were any results, you can simply return a 1 or a 0. This kind of boolean response takes minimal bandwidth and minimal processing, and the best thing about it is all you need to do is evaluate it as a boolean on the client side - i.e. if (result) { /* do stuff */ }
i've been creating functions for too long without taking my code to 'classes'.
I learn well through example and I just wanted to convert this simple function into a class so I can compare something I know with something I don't...
Take the following function:
function affiliateName($affiliateID) {
$sql = 'SELECT * FROM affiliates WHERE uID="' . $affiliateID . '" ';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$affiliateName = $row['firstName'] . ' ' . $row['lastName'];
return $affiliateName;
}
And how would I make that a class?
<?php
class AffiliateModel
{
public function first($id)
{
$sql = 'SELECT *, CONCAT(firstName, ' ', lastName) AS qualifiedName FROM affiliates WHERE uID="' . $id . '" LIMIT 1';
$res = mysql_query($sql);
return mysql_fetch_object($res);
}
}
$model = new AffiliateModel();
$a = $model->first($id);
echo $a->qualifiedName;
?>
Hope it helps
<?php
class affiliate{
// fields or properties
public $name = '';
public $id = 0;
// constructor
public function affiliate($id = 0){
$this->set_ID($id);
}
// methods
public function set_ID($id){
return $this->id = $id;
}
public function get_Name(){
if($this->name != ""){
$sql = 'SELECT * FROM affiliates WHERE uID="' . $this->id . '" ';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
return $this->name = $row['firstName'] . ' ' . $row['lastName'];
}else{
return $this->name;
}
}
}
// Example:
$currentAffiliate = new affiliate(153);
echo $currentAffiliate->name;
?>
I prefer the following design as it is the simplest to use:
class affiliates {
static function load($id) {
return new self(intval($id));
}
private function __construct($id) {
$query = "SELECT * FROM affiliates WHERE id = " . intval($id);
$result = mysql_query($query);
// TODO: make sure query worked
foreach(mysql_fetch_assoc($result) as $field => $value)
$this->$field = $value;
}
// composite fields - made by combining and/or re-formatting other fields
function qualifiedName() {
return $this->firstName . ' ' . $this->lastName;
}
function properName() {
return $this->lastName . ', ' . $this->firstName;
}
}
$a = affiliates::load(22);
// all db fields are available as properties:
echo $a->id; // 22
echo $a->firstName; // Fred
echo $a->lastName; // Smith
// composite fields are methods
echo $a->qualifiedName(); // Fred Smith
echo $a->properName(); // Smith, Fred
// to get a single field from a particular person
echo affiliates::load(72)->qualifiedName();