PHP / mySQL - in_array and Get Result - php

I have an array like below and that array refers to another data on my db,
Array
(
[0] => 4
[1] => 1
[2] => 15
[3] => 1
[4] => 1
)
how do I want to select value no 1, and get the most top value from table that has value=1?
I use in_array(1,$array) but it does not output anything. Below are my coding;
$sql = " Select * FROM table_name WHERE staff_id='".$_SESSION['staff_id']."' ORDER BY table_name DESC ";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
$leave_id= array();
while($row_permohonan=mysqli_fetch_assoc($result_permohonan))
{
$leave_available = $row_permohonan['leave'];
$leave_id[] = $row_permohonan['leave_id'];
} mysqli_free_result($result_permohonan);
//echo '<pre>'; print_r($leave_id); echo '</pre>';
if(in_array(1,$leave_id)){
echo $leave_available .'/'.$row['total_leave'];
}

I think you have missed $result.
$sql = " Select * FROM table_name WHERE staff_id='".$_SESSION['staff_id']."' ORDER BY table_name DESC ";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
$leave_id= array();
while($row_permohonan=mysqli_fetch_assoc($result)) //Here
{
$leave_available = $row_permohonan['leave'];
$leave_id[] = $row_permohonan['leave_id'];
} mysqli_free_result($result); //And here

First, your code is not clear. You are using:
echo $leave_available.'/'.$row['total_leave'];
Where "$row" is not set anywhere into your code. If you have put on top of your code:
ini_set("display_errors", "On"); error_reporting(E_ALL);
PHP would break with a fatal error if you are executing the code exactly as you gave it. But I assume that you set it somewhere else into your code.
2nd: You should return the data you want into your MySQL query. If you just want to know if there is at least 1 row into your database having leave_id=1 and staff_id=$_SESSION['staff_id'], then add this condition in your SQL query:
$sql = "Select COUNT(*) AS nbrows FROM table_name WHERE staff_id='".$_SESSION['staff_id']."' AND leave_id=1 ORDER BY column_name DESC ";
And then: you have to use "ORDER BY" statement with a column name and not the table name.
Using "in_array": as you are matching "1", I would recommend you to add "true" as 3rd parameter of this function (force using "strict comparison" in case sensitive and type matching):
in_array(1, $array, true)
Then, you'll also have to cast your $leave_id result:
$leave_id[] = (int)...
(int) cast the string value to integer (as PHP results from database are almost strings)

Related

PHP MySQL dont get last selected

i have a mysql Table with some rows.
The Select gets one (LIMIT 1) row. After a counter it reloads and get random another row. But sometimes he get the same (cause random).
How can i setup that he dont get the last row?
The problem is, i cannot do that in mysql. I must do that in the SESSION or only on that site.
I tried that:
$_SESSION['ads'] .= ','.$adid;
put that adid in "ads" SESSION and read it before SELECT here
session_start();
$ads = substr($_SESSION['ads'], 1);
$ads = str_replace(",", "','", $_SESSION['ads']);
In the SELECT is that
AND id NOT IN ('".$ads."')
But sometimes, i dont know why, he save two items or something... i dont find out why, cause the SELECT is LIMIT 1
Any ideas how to do that or is there a mysql function?
For any reason, the script is load two times the SELECT or something
This is the code:
$query = "SELECT * FROM ads ORDER BY RAND() LIMIT 1;";
while($row = $result->fetch_assoc()) {
$adid = $row["id"];
$_SESSION['ads'][] = $adid;
}
echo 'adid: '. $adid;
print_r($_SESSION['ads']);
There he print like that:
Array
(
[0] => 6
[1] => 3
)
I dont know, why he puts 2 in there. Cause the echo of the $adid shows only one!
Try something like this maybe :
1/ Create a new session and create an empty array :
session_start();
if (empty($_SESSION['ads']))
$_SESSION['ads'] = array();
2/ Do you select and add the id in this array :
if (empty($_SESSION['ads']) {
// 1. Do your select with no where condition
// 2. Fetch the result
$data = /* result of the select */;
// 3. Add the selected id in your session array
$_SESSION['ads'][] = $data['id'];
} else {
// 1. Do your select but with a WHERE condition
$query = "SELECT...
WHERE id NOT IN ( " . implode( "', '" , $_SESSION['ads'] ) . " )";
// 2. Fetch the result
$data = /* result of the select */;
// 3. Add the selected id in your session array
$_SESSION['ads'][] = $data['id'];
}
Is it what you are looking for?

MySql NOT IN many values from the mysql fetched result

I have 2 MySql queries which are interdependent.
My 'table1'
----------
id
----------
1
2
3
4
5
6
7
My First query
$sql1 = "SELECT * FROM table1 WHERE";// some condition which gives me id's 1,2,3
$res1=$obj->_executeQuery($sql1);
$res1=$obj->getAll($res1);
The result of this is giving me array
Array
(
[0] => Array
(
[id] => 1
..
..
)
[1] => Array
(
[id] => 2
..
..
)
[2] => Array
(
[id] => 3
..
..
)
)
I want to run another query on same 'table1', where not equal to list of ID's which i am getting from the first query.
My Second Query
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (" . implode(',', $res1) . ")";
This is not showing me only one id i,e first. In above case i should get id's 4,5,6,7
Since implode will not give the desired value on multidimensional array so first you need to get the array of all id's to form one-dimensional array then use implode on the array of id's:
$id=array();
foreach ($res1 as $key=>$inner_array){
$id[]= $inner_array['id'];
}
you can use array_walk also here like this:
array_walk($res1,function($c) use (&$id) {$id[] = $c['id'];});
but i think the best one is array_map :
$id = array_map(function($i) {
return $i['id'];
}, $res1);
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (" . implode(',', $id) . ")";
Note: when ever you are doing select please specify your column if you need few to select,unnecessarily selecting all will slow your sql processing.
suppose here:SELECT * FROM table1 WHERE, if you need only id then please select id only.
You have to change $res1, which is a two-dimensional array, into a one-dimensional array of IDs to be able to use implode:
$ids_from_first_query = array();
foreach($res1 as $result_row) {
$ids_from_first_query[] = $result_row['id'];
}
$ids_as_string = implode(',', $ids_from_first_query);
$sql2 = 'SELECT * FROM table1 WHERE id NOT IN(' . $ids_as_string . ')';
In the above code, $ids_as_string will look like this:
1,2,3
Thus it can be used in your MySQL query
Here you are getting two dimensional array so that's reason it is not working
while($each=mysql_fetch_array($res1))
{
$array[]=$each[id];
}
$imp=implode(",",$array);
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (".$imp.")";
Try this it will works

MySQL join results different in PHP?

I have a query:
SELECT * FROM categorys
LEFT JOIN category_info ON categorys.cat_id=category_info.cat_id
WHERE `cat_name` = 'aname'
ORDER BY `cat_order`
When I run this in phpMyAdmin I get an cat_id back regardless of if there is a match in the second table.
However, when I run this query in my PHP code I get a blank cat_id back, as shown by this print_r():
Array ( [cat_id] => [cat_name] => baths [type] => main [cat_order] =>
99 [cat_img] => [display] => 1 [deleted] => 0 [desc_id] => [desc] =>
[text] => )
Why would there be a different result when the query is exactly the same?
EDIT:
My PHP code:
$getcatidsql = "SELECT * FROM categorys
LEFT JOIN category_info ON categorys.cat_id=category_info.cat_id
WHERE `cat_name` = '{$cname}'
ORDER BY `cat_order";
$getcatidresult = $db->query( $getcatidsql );
$catdata = $db->fetchRow( $getcatidresult );
function query() {
$this->query_total++;
if (func_num_args() == 1) {
$sql = func_get_arg(0);
} else {
$args = func_get_args();
for ($i=1;$i<count($args);$i++) if (!is_numeric($args[$i])) $args[$i] = '"'.mysql_real_escape_string($args[$i]).'"';
$sql = vsprintf(array_shift($args),$args);
}
if ($result = mysql_query($sql,$this->db_connection)) {
return $result;
} else {
$this->dberror( $this->db_connection, $sql );
}
}
function fetchRow($result,$type=MYSQL_ASSOC)
{
if($result)
$row = mysql_fetch_array($result,$type);
return $row;
}
I think you must not use select * (also because of same column names in both tables) , but select exactly fields for your needs
select table_name.field, table_name.field2, other_table_name.field1
.. and you'll get right results from both php code and phpmyadmin
I think it is because 'cat_id' is the same field name in both tables => the same index in result array.
Try to modify query like : " Select categorys.cat_id AS category from categorys ..... "
You're SELECTing * from categorys and category_info. They both have a cat_id column. So you'll get two cat_id columns back.
The question is: what does the SQL library/driver you're using do when it encounters two columns with the same name in your SELECT list?
Looks like it's probably overwriting the first one it comes across with the second one... What happens if you use an explicit SELECT list, specifying categorys.cat_id and not bringing in category_info.cat_id?
When you state
When I run this in phpMyAdmin I get an cat_id back
Do you mean that you get a VALUE for cat_id or do you get it as NULL? Because that is what you get with php, a NULL value for cat_id (as you see in print_r it still appears there).
If you don't want to get lines from categorys where there is no existing line in category_info for that category, then you have to use RIGHT JOIN instead of LEFT JOIN.

How to mysql_query from same table with different where clause in same php file

I have a table containing 4 articles with id 1,2,3 and 4 as well as ordering value 1,2,3,4.
They have separate columns for their title, image etc. I need to get them distinctly with where clause. So i did:
For article 1:
//topstory1
$sql_topstory1 ="SELECT * FROM topstory WHERE story_active='1' && story_order='1'";
$result_topstory1 = mysql_query($sql_topstory1);
$row_topstory1 = mysql_fetch_array($result_topstory1);
$story1_title = $row_topstory1['story_title'];
$story1_abstract = $row_topstory1['story_text'];
And for article 2
//topstory2
$sql_topstory2 ="SELECT * FROM topstory WHERE story_active='1' && story_order='2'";
$result_topstory2 = mysql_query($sql_topstory2);
$row_topstory2 = mysql_fetch_array($result_topstory2);
$story2_title = $row_topstory2['story_title'];
$story2_abstract = $row_topstory2['story_text'];
As I have to reuse them in a page.
PROBLEM IS, the first query works but the second one doesn't. It seems like MySql cannot execute two consecutive queries on the same table in a single php file. But I think there is a simple solution to this...
Please help me soon :( Love you guys :)
There are several possible reasons for the second query to fail, but the fact that it's the second query in the file does not cause it to fail.
I would expect that article 2 does not have the active flag set to 1, causing you to get an empty result set.
Another option is that you may have closed the mysql connection after the first query, then you can't execute another query. (General rule: don't close database connections. PHP takes care of that.)
Why not just get them both with 1 query?
$sql_topstory ="SELECT * FROM topstory WHERE story_active='1' && story_order IN(1, 2) ORDER BY story_order DESC";
$result_topstory = mysql_query($sql_topstory) or trigger_error('Query Failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result_topstory)) {
$title[] = $row['story_title'];
$abstract[] = $row['story_abstract'];
}
// Then to display
echo 'Story 1 is ' . $title[0] . ' with an abstract of ' . $abstract[1];
There are plenty of ways to do this, this is just a simple demonstration.
$query = <<<SQL
SELECT
story_title
, story_text
FROM
topstory
WHERE
story_active
ORDER BY
story_order ASC
SQL;
$result = mysql_query($query);
$stories = array();
while ($row = mysql_fetch_assoc($result)) {
$stories[] = $row;
}
Now you have an array of stories like so:
array(
0 => array(
'story_title' => ?
, 'story_text' => ?
)
, 1 => array(
'story_title' => ?
, 'story_text' => ?
)
)
Should be pretty easy to iterate through.

MySQL (exploding/matching array)

Question1:
MySQL table
id | array
1 | 1,2,3
2 | 2
3 | 2,3
4 | 4,5,6
$_GET['id'] = 2;
$a = mysql_query("SELECT * FROM `table` WHERE `array` ??? '$_GET[id]'");
In this step, I want to run through the entire array and see if it matches with the $_GET['id'], so it should output:
ids: 1,2,3
Question2:
MySQL table
id | array
1 | 4,5,6
2 | 3,4,7
$_GET['id'] = 4;
$a = mysql_query("SELECT * FROM `table` WHERE `array` ??? '$_GET[id]'");
In this step, I only want to match against the first element in the array, so it should output:
id: 4
I can only think of using PHP to do this, but I'd rather do all that just within the MySQL query, if that is even possible.
$a = mysql_query("SELECT * FROM `table`");
while($b = mysql_fetch_assoc($a))
{
$elements = explode(',', $b['array']);
foreach($elements as $element)
{
if($element == $_GET['id'])
{
echo $b['id'].'<br />';
}
}
}
or
$a = mysql_query("SELECT * FROM `table`");
while($b = mysql_fetch_assoc($a))
{
$array = $b['array'];
if(in_array($_GET['id'], $array))
{
echo $b['id'].'<br />';
}
}
that would look just awful.
That you can/should structure your database differently has already been mentioned (see http://en.wikipedia.org/wiki/Database_normalization). But....
See FIND_IN_SET()
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
-> 2
e.g.
<?php
$mysql = init();
bar($mysql, 1);
bar($mysql, 2);
bar($mysql, 3);
bar($mysql, 4);
function bar($mysql, $x) {
$sql_x = mysql_real_escape_string($x, $mysql);
$result = mysql_query("SELECT id, foo FROM soTest WHERE FIND_IN_SET('$sql_x', foo)", $mysql) or die(mysql_error());
echo "$x:\n";
while( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo $row['id'], ' ', $row['foo'], "\n";
}
echo "----\n";
}
function init() {
$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error());
mysql_query('CREATE TEMPORARY TABLE soTest (id int auto_increment, foo varchar(64), primary key(id))', $mysql) or die(__LINE__.' '.mysql_error());
mysql_query("INSERT INTO soTest (foo) VALUES ('1,2,3'), ('2,4'), ('3'), ('2,3'), ('1,2')", $mysql) or die(__LINE__.' '.mysql_error());
return $mysql;
}
prints
1:
1 1,2,3
5 1,2
----
2:
1 1,2,3
2 2,4
4 2,3
5 1,2
----
3:
1 1,2,3
3 3
4 2,3
----
4:
2 2,4
----
MySQL can't use indices to perform this search, i.e. the query results in a full table scan, see Optimizing Queries with EXPLAIN
edit:
For your second question you only have to change the WHERE-clause to
WHERE FIND_IN_SET('$sql_x', foo)=1
Your data structure in the DB is not optimal for querying the way you want it.
For the first question:
mysql_query("SELECT * FROM table WHERE array LIKE '%,$_GET[id],%' OR array LIKE '$_GET[id],%' OR array LIKE '%,$_GET[id]' OR array = '$_GET[id]'");
For the second:
mysql_query("SELECT id, SUBSTR(array, 1, POSITION(',' IN array) - 1) AS array FROM table WHERE array LIKE '$_GET[id],%' OR array = '$_GET[id]'");
As you can see, these queries aren't pretty, but they'll do what you want.
Untested, but you should be able to use:
Question 1:
SELECT * FROM table WHERE array REGEXP '(^|,)?(,|$)';
// Match either the start of the string, or a , then the query value, then either a , or the end of the string
Question 2:
SELECT * FROM table WHERE array REGEXP '^?(,|$)';
// Match the start of the string, then the query value, then either a , or the end of the string
Where ? is replaced with your $_GET value.
No idea on the performance of this.
I'd recommend you to bring your database to the first normal form, e. g.
CREATE TABLE t_master (
id INT PRIMARY KEY AUTO_INCREMENT
);
CREATE TABLE t_array (
id INT PRIMARY KEY AUTO_INCREMENT,
master_id INT NOT NULL,
value INT,
CONSTRAINT fk_array_master_id FOREIGN KEY (master_id) REFERENCES t_master (id)
);
Then you can find records in t_master that have a specific value with
$q = 'SELECT m.* ' .
'FROM t_master AS m INNER JOIN t_array AS a ON a.master_id = m.id ' .
"WHERE a.value = '" . mysql_real_escape_string($_GET['id'], $db) . "' " .
'GROUP BY m.id';
The most important advantage is that if you have a lot of values, you can add an index to find them much faster:
ALTER TABLE t_array ADD INDEX idx_value (value);
A less evident, but not the last advantage is that your queries become more logical and structured.
If you can't normalise your schema (which is the best option:
SELECT *
FROM table
WHERE ','+array+',' LIKE '%,$_GET[id],%'
But if you need to access the records by id, then you really should normalise
First One:
SELECT * FROM table WHERE array LIKE '$_GET[id],%' OR array LIKE '%,$_GET[id],%' OR array LIKE '%,$_GET[id]' OR array = '$_GET[id]
Second One:
SELECT * FROM table WHERE array LIKE '$_GET[id],%' OR array = '$_GET[id]
Explanation:
'$_GET[id],%' will match, if array is start with $_GET[id]
'%,$_GET[id],%' will match, if $_GET[id] is between any two of array items
'%,$_GET[id]' will match, if array is end with $_GET[id]
array = '$_GET[id]' match, if the array contains only one item equal to $_GET[id]

Categories