php function not cycling through all users, just first user - php

the following php function is only working for one user record, not all user records with a value of "1" in the weekly_email_f1 column, any ideas?
function getSummaryEmailInfo() {
$sql = "
SELECT u.id, u.master_id, u.email
FROM user AS u
WHERE u.weekly_email_fl = 1
";
$query = $this->db->query( $sql );
$users = $query->result_array();
foreach ( $users as &$user ) {
$user_id = ( $user['master_id'] == '0' ) ? $user['id'] : $user['master_id'];
$sql = "
SELECT ui.custom_name
FROM user_item AS ui
WHERE ui.user_id = '" . $user_id . "'
AND added_to_list_dt IS NOT NULL
ORDER BY added_to_list_dt DESC
;
";
$query = $this->db->query( $sql );
$user['s_list'] = $query->result_array();
}
return $users;
}
There are multiple users with weekly_email_f1 = 1. i think there is something wrong with how the result_array(); is being populated but cannot figure it out, yet...
function getUserInfo( $user_id ) {
$query = $this->db->query( "
SELECT name AS first_name, email, zip_code, weekly_email_fl
FROM user
WHERE id = '" . $user_id . "'
;" );
if ( $query->num_rows() > 0 ) {
$results = $query->result_array();
$results = $results[0];
} else {
$results = null;
}
return $results;
}

while($users = $query->result_array()) {
/* You can use $users['master_id'] here */
}

There is only 1 user with weekly_email_f1 = 1
$query->result_array(); returns only first/last/one row.

Related

After fetching a value from DB then assign it to a variable, then i can't use it to the next query

This is my model:
public function GetStudentData()
{
$sID = $this->input->get('id');
$class_id = $this->db->query("SELECT student.class_id FROM student WHERE student.sID = '$sID'");
$query = $this->db->query("SELECT * FROM student WHERE(sID='$id'AND class_id = '$class_id')");
if($query->num_rows() > 0)
{
return $query->row();
}else{
return false;
}
}
How can I use $class_id in the next query?
you could do it in one query... (from your example [SIC])
public function GetCSData() {
$id = $this->input->get('id');
$query = $this->db->query("SELECT student.*
FROM student
WHERE student.sID = '$id'
AND student.class_id = (SELECT class_id
FROM student
WHERE student.sID = '$id')");
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}//..GetCSData end
looking at it though, that will give the same result as
SELECT *
FROM student
WHERE sID = '$id'
maybe I am missing a point?

php with framework of codeigniter

function invitation_result()
{
$this->load->database();
$user_id = $_GET['user_id'];
$qry = mysql_query("select * from sent_invitations where user_id='$user_id'");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$mobile_number = $row['mobile_number'];
$qry1 = mysql_query("select mobile_number from users where mobile_number = '$mobile_number'");
$row1 = mysql_fetch_array($qry1);
$mobile_number = $row1['mobile_number'];
$users[] = array('mobile_number' => $mobile_number );
return $users;
}
}
}
The above is my coding.
In sent_invitation table there are 3 rows with user_id=11.
from there i m trying to get mobile_number of all three rows based on user_id.
the mobile_number of all 3 rows is different.
after geting mobile_number from sent_notification table.
i m comparing the mobile_number with mobile_number of users table.
i m seeing that 3 of them mobile_numbers are there in users table.
i m trying to show all of them.
bt problem is that my code id showing only one row and that is of last mobile number from 3
Since you are using Codeigniter You should follow the MVC pattern :
So the code in the controller should be :
public function invitation_result(){
$userId = 0;
if(($_GET['user_id']) && is_numeric($_GET['user_id']) && $_GET['user_id'] > 0){
$userId = $_GET['user_id'];
}
$data = $this->User_model->getDataFromID($userId);
return $data;
}
And the code for Model should be :
public function getDataFromID($userId){
$arrReturn = array();
if(($userId) && is_numeric($userId) && $userId > 0){
$this->db->select('*');//You can put the required fields here like : name,mobile_number...
$this->db->from('sent_invitations');
$this->db->where("user_id",$user_id);
$query = $this->db->get();
$result = $query->result_array();
if(!empty($result)){
foreach($result as $key=>$value){
$this->db->select('*');
$this->db->from('mobile_number');
$this->db->where("mobile_number",$value['mobile_number']);
$querySub = $this->db->get();
$resultSub = $querySub->result_array();
if(!empty($resultSub)){
array_push($arrReturn,$resultSub);
}
}
return $arrReturn;
}
}else{
return $arrReturn;
}
}
By the time I have written the Answer you would have solved the error ,but this answer will help future Users.
You should use while loop where you are getting mobile_number in inner loop.
function invitation_result()
{
$this->load->database();
$user_id = $_GET['user_id'];
$qry = $this->db->query("select * from sent_invitations where user_id='$user_id'");
if ($qry->num_rows() > 0)
{
while ($qry->result_array() as $row)
{
$mobile_number = $row['mobile_number'];
$qry1 = $this->db->query("select mobile_number from users where mobile_number = '$mobile_number'");
if($qry1->num_rows() > 0){
while($qry1->result_array() as $row1){
$mobile_number = $row1['mobile_number'];
$users[] = array('mobile_number' => $mobile_number );
}
return $users;
}
}
}
}
You should use codeigniter database query instead of mysql custom query. because mysql is deprecated. You can use below code:
function invitation_result()
{
$this->load->database();
$user_id = $_GET['user_id'];
$qry = mysqli_query("select * from sent_invitations where user_id='$user_id'");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$mobile_number = $row['mobile_number'];
$qry1 = mysql_query("select mobile_number from users where mobile_number = '$mobile_number'");
$row1 = mysql_fetch_array($qry1);
$mobile_number = $row1['mobile_number'];
$users[] = array('mobile_number' => $mobile_number );
return $users;
}
}
}
first, can you simplified the query something like this ?
$sql = "select a.*, b.mobile_number as user_mobile_number
from sent_invitations a
join users b on a.user_id = b.user_id";
or
$sql = "select a.*, b.mobile_number as user_mobile_number
from sent_invitations a
join users b on a.mobile_number = b.mobile_number";
it's depend on how this two tables can be related.
Now you can see if the sent_invitations.mobile_number also found in users.mobile_number just in one query. If this returns multiple same rows, then put distinct keyword after SELECT
second, back to your code, i think you should move return $users out form while block
while ($row = mysql_fetch_array($qry)) {
// your code
}
return $users;
good luck;
function invitation_result()
{
$this->load->database();
$user_id = $_GET['user_id'];
$qry = $this->db->query("select * from sent_invitations where user_id='$user_id'");
$results = $qry->result();
foreach ($results as $result)
{
$mobile_number = $result->mobile_number;
$qry1 = $this->db->query("select mobile_number from users where mobile_number = '$mobile_number'");
$results1 = $qry1->result();
foreach ($results1 as $result1)
{
$row1 = mysql_fetch_array($qry1);
$mobile_number = $result1->mobile_number;
$users = array('mobile_number' => $mobile_number );
return $users;
}
}
}

Dynamically create a SQL statment from passed values in PHP

I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.

Using recurssion in deleting parent and child relationship in mysql table

I'm having trouble getting this function work. This is my database design
I'm working in an application wherein when a user deletes a parent category, all the subcategory would also be deleted, and so on and so fort..
For example:
When the user clicks on the "Test1" category in my application, the "Test1.1" and "Test1.1.1" would be deleted since it is under the "Test1" category.
This is my database design(above).
This is the code that I wrote:
function DeleteProjectPhotos( $cat_id ) {
$sql = "SELECT * FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
$sql = "SELECT * FROM project_category WHERE parent_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
while( $row = mysql_fetch_assoc( $query ) ) {
$this->DeleteProjectPhotos( $row['category_id'] );
}
} else {
$sql = "DELETE FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
}
}
}
But I think the whole logic here is wrong because when I try to delete the category_id 33, everything won't be deleted. Kindly teach me how to do this one.
Your help would be greatly appreciated and rewarded!
Thanks! :)
<?php
$catID = $_GET['catID'];
deleteCategory($catID);
function connect(){
$host = 'localhost';
$dbName = 'sony';
$userName = 'root';
$password = '';
$conn = new PDO("mysql:host=$host;dbname=$dbName",$userName,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;
}
$stmt = '';
function deleteCategory($catID){
$conn = connect();
$tableName = 'childparent';
$sql = "select catID from $tableName where parentID = :catID";
global $stmt;
$stmt = $conn->prepare($sql);
$idsToDelete = getChilds($catID);
$idsToDelete[] = $catID;
//print_r($idsToDelete);
$delExp = '';
foreach($idsToDelete as $id)
$delExp .= " catID=$id or";
$delExp = preg_replace('/or$/','',$delExp);
if($delExp != ''){
$delSql = "delete from $tableName where $delExp";
//echo $delSql;
$delStmt = $conn->prepare($delSql);
$delStmt->execute();
}
}
$collectedIDs = array();
function getChilds($catID){
global $stmt,$collectedIDs;
$stmt->bindValue(':catID',$catID);
$stmt->execute();
$childCatIDs = array();
while($row = $stmt->fetch(pdo::FETCH_ASSOC)){
$childCatIDs[] = $row['catID'];
$collectedIDs[] = $row['catID'];
}
//print_r($childCatIDs);
//die();
if(!empty($childCatIDs)){
foreach($childCatIDs as $cid)
getChilds($cid);
}
return $collectedIDs;
}
?>
If you don't want triggers you can try http://php.net/manual/en/function.mysql-affected-rows.php on delete category you get it`s id and while there is a return you try to delete by cathegory or by parent

Codeigniter modify database query array item

I'm attempting to modify a date field from my database before it gets outputted to the view, but I'm not having much luck. This code doesn't seem to work, what am I doing wrong?
function get_journal_entry($id)
{
$sql = 'SELECT * FROM journal WHERE user_id = '.$this->tank_auth->get_user_id().' AND id = '.$id;
$query = $this->db->query($sql);
$query['created'] = date("c", strtotime($query['created']));
return $query->row_array();
}
$this->db->query returns a query object, not your results. You need to modify the row after calling $query->row_array.
$query = $this->db->query($sql);
$result = $query->row_array();
$result['created'] = date("c", strtotime($result['created']));
return $result;
Another version of the code, which may work:
function get_journal_entry($id)
{
$sql = 'SELECT * FROM journal WHERE user_id = ' . intval($this->tank_auth->get_user_id()) . ' AND id = ' . intval($id);
$row = $this->db->query($sql)->row_array();
$row['created'] = date("c", strtotime($row['created']));
return $row;
}

Categories