How to use a numeric array constant array in MySQL query? - php

constant ex: define('PERMANENT_EMPLOYEE',array('1,'2','3'));
SELECT * from employee where id IN('PERMANENT_EMPLOYEE');
this above select is not working .

you need to pass a string, as you are using array right now
define("PERMANENT_EMPLOYEE","'1','2','3'");
echo 'SELECT * from employee where id IN ('.PERMANENT_EMPLOYEE.')';
I have checked it in this way

You can not assign an array to constant. Try doing it in this way:
define('PERMANENT_EMPLOYEE', json_encode(array('1','2','3')));
$sql = 'SELECT * from employee where id IN(' . implode(',', json_decode(PERMANENT_EMPLOYEE, true)) . ')';

Use PHP join function then write your query as below:-
$ids = join(',',[1,2,3]);
$sql = "SELECT * FROM employee WHERE id IN ($ids)";
If you want to use array via constant then you should use serialize,
define('PERMANENT_EMPLOYEE',serialize(array(1,2,3)));
$ids = join(',',unserialize(PERMANENT_EMPLOYEE));
$sql = "SELECT * FROM employee WHERE id IN ($ids)";

Related

Issue with rand() function in PHP

I'm having a little trouble with my rand() function. I have the following query:
$listTrainers = mysqli_query($conn, "SELECT emp_id FROM employees;");
while($fetchTrainers = mysqli_fetch_row($listTrainers))
{
echo 'ID: ' . $fetchTrainers['0']. '<br>';
}
This query returns me the id of all employees in the database, is there a way I can randomly select one of these id's and store it in a variable?
I am trying to use the following function:
echo(rand(begin, end));
where begin is the first element from the query and end is the last element
add this to your query:
ORDER BY RAND() LIMIT 1
You can do so within your query easily
SELECT emp_id FROM employees ORDER BY RAND() LIMIT 1
The easiest way is to do this directly in the database, to avoid getting all IDs if you only need one:
SELECT
emp_id
FROM
employees
ORDER BY
RAND()
LIMIT
1
If you do need all IDs, but additionally want to pick a random one, use this to avoid querying the database twice:
$listTrainers = mysqli_query($conn, "SELECT emp_id FROM employees;");
while($fetchTrainers = mysqli_fetch_row($listTrainers))
{
$id = $fetchTrainers[0];
echo 'ID: ' . $id . '<br>';
$ids[] = $id;
}
$randomId = $ids[array_rand($ids)];

PHP: How to insert array value into mysql statement

i have this array and get it from from an url. this array is member id that i need to pass to mysql.
$member_id = $_GET['member_id'];
the array like this : Array ( [0] => 1269 [1] => 385 )
how can i transfer this array into my mysql statement and make , become AND :
$answer_sql = mysql_query("SELECT tna_category. * , tna_question. *, tna_answer. *
FROM tna_category, tna_question, tna_answer
WHERE tna_category.section_id = '$section_id1'
AND tna_question.id = tna_answer.question_id AND tna_question.category_id = tna_category.id
AND tna_answer.member_id = ['1269' , '385']
ORDER BY tna_answer.question_id");
should i put bracket?..
in this part : tna_answer.member_id = Array or $member_id
As others have said, you can use IN() but you are apparently open to SQL injection attacks as it is. You need to do this:
$escaped_ids = array_map('mysql_real_escape_string', $member_ids);
Or, if they are surely all integers
$escaped_ids = array_map('intval', $member_ids);
Then, you can write your query like:
$query = "SELECT tna_category. * , tna_question. *, tna_answer. *
FROM tna_category, tna_question, tna_answer
WHERE tna_category.section_id = '" . mysql_real_escape_string($section_id1) . "'
AND tna_question.id = tna_answer.question_id
AND tna_question.category_id = tna_category.id
AND tna_answer.member_id IN (".implode(",", $escaped_ids).")
ORDER BY tna_answer.question_id";
Never, never, never put unescaped values in your query.
Also, you should not be using the mysql_ functions anymore. Please consider using the mysqli_ functions instead.
First split the array value, get no. of rows in the array value and pass the value one by one into the query by using for or foreach loop.
try this
$member_id = $_GET['member_id'];
If you're already getting comma seprated values then there's no need to use explode function just use implode function in database query.
$member_id = explode(",", $member_id);
and then
answer_sql = mysql_query("SELECT tna_category. * , tna_question. *, tna_answer. *
FROM tna_category, tna_question, tna_answer
WHERE tna_category.section_id = '$section_id1'
AND tna_question.id = tna_answer.question_id AND tna_question.category_id = tna_category.id
AND tna_answer.member_id IN (".implode(",", $member_id).")
ORDER BY tna_answer.question_id");
the explode function create array it depends on you explode value with comma OR space and then implode mean join these values with comma OR space.
for more detail explode and implode.
you can use IN clause of mysql like this
$your_array = array("0"=>"1269", "1"=>"385");
$in_text = implode(",", $your_array);
$sql = "SELECT tna_category. * , tna_question. *, tna_answer. *
FROM tna_category, tna_question, tna_answer
WHERE tna_category.section_id = '$section_id1'
AND tna_question.id = tna_answer.question_id
AND tna_question.category_id = tna_category.id
AND tna_answer.member_id IN ($in_text)
ORDER BY tna_answer.question_id";

PHP Retrieve results

I am having a small trouble retrieving results that I hope someone can help me with.
I have a field called $incategory which is a comma based string, and what I want to do is explode the into an array that can be used to retrieve results as below (Hope that makes sense):
<?php
$showlist = $row_listelements['incategory'];
// ** e.g. $incategory = 1,3,5,
// ** What I want to do is look at table 'category'
// ** and retrieve results with an 'id' of either 1, 3 or 5
// ** Display Results
mysql_select_db($database_db, $db);
$query_display = "SELECT * FROM category WHERE id = ".$showlist." ORDER BY name ASC";
$display = mysql_query($query_display, $db) or die(mysql_error());
$row_display = mysql_fetch_assoc($display);
$totalRows_display = mysql_num_rows($display);
?>
You can use the IN keyword of SQL directly like this.
query_display = "SELECT * FROM category WHERE id IN (".$showlist.") ORDER BY name ASC";
Another tip would be to stop using MYSQL_QUERY as it is deprecated in PHP 5.3
Edit: If $showlist = '1,3,5,' you will need to remove the last comma from the string to make it useable in the query. Just use this query then
query_display = "SELECT * FROM category WHERE id IN ('".str_replace(",", "','", substr($showlist, -1))."') ORDER BY name ASC";
Use explode function and use , as delimiter.
refer here http://www.w3schools.com/php/func_string_explode.asp
Hope this helps.
First, you have explode the $incategory string into an array containing all of the category number. For example:
$incategory = explode(",", $incategory);
And then you just have to execute this query:
$query_display = "SELECT * FROM category WHERE id = "
. $incategory[$i] . " ORDER BY name ASC";
The $i should be defined beforehand (usually using loop).

How can I SELECT data which one field are member of an array?

Use PHP and MySQL. I have an array, P, which contains the value of possible category number of products. In my table it also have the field "category" which stored category number and the others. What I want is to SELECT data in all rows which field "category" have any value in array P.What should I do?
For example
P=[1,7,13]
SELECT * FROM table WHERE category=P[1] OR categry=P[2] OR category=P[3]....
Use:
$categories = implode(', ', $p); // Where $p is the array
SELECT * FROM table WHERE category IN ($categories)
Try implode() function :
$sql = "SELECT * FROM table WHERE category IN (".implode(",", $P).")"
You should use IN keyword:
SELECT * FROM table WHERE category IN (p[1], p[2], p[3])
with implode:
$categories = implode(',', $P);
Use string concatenation:
$P = array(1, 7, 13);
$query = "SELECT * FROM table WHERE category=".$P[1]." OR
category=".$P[2]." OR category=".P[3]."....";
or
$query = "SELECT * FROM table WHERE category={$P[1]} OR
category={$P[2]} OR category={P[3]}....";

WHERE id=(array)

The code below only outputs single line(there are 2 in database that should be outputed).
I think that problem is in id=$data[id] since data1 is array instead of single value.I hoped that while will fix that but it doesnt look too good...
$results1 = mysql_query("SELECT * FROM keywords WHERE keyword='$search' ORDER BY (relevant-irrelevant) DESC");
$data1=mysql_fetch_array($results1);
$results2=mysql_query("SELECT * FROM searchengine WHERE id='$data1[id]'");
while($data2=mysql_fetch_array($results2))
First, isolate your ids, looping to get all of the results:
$ids = array();
while ( $data1 = mysql_fetch_array($results1) ) {
$ids[] = $data1['id'];
}
Then, convert your $ids array into a string. An easy way to do this is via implode():
$results2=mysql_query(
"SELECT * FROM searchengine WHERE id IN (" . implode(',', $ids) . ")"
);
Maybe I´m missing something, but how can $data1['id'] be an array? it´s probably an integer and perhaps a string, but it's not an array. $data1['id'] is a single value; the value of field id in the keywords table
I think you just need to put curly quotes around the variable:
$results2=mysql_query("SELECT * FROM searchengine WHERE id='{$data1[id]}'");
or even better:
$results2=mysql_query("SELECT * FROM searchengine WHERE id=" . (int) $data1['id']);
If id is an integer that is.
And of course if the first query returns more than 1 result, you will have to loop through them as well.
Couldn't you just select the entire thing in one query?
SELECT *
FROM keywords k
searchengine s
WHERE k.keyword='$search'
AND k.id = s.id
$results1 = mysql_query("SELECT * FROM keywords WHERE keyword='$search' ORDER BY (relevant-irrelevant) DESC");
$data1=mysql_fetch_array($results1);
//VERY DANGEROUS TO USE USER INPUT
$in = join(',',$data1['id']);
$results2=mysql_query("SELECT * FROM searchengine WHERE id IN ({$in})");
while($data2=mysql_fetch_array($results2))
You can't pass array as condition. You should:
a. do a for(each) loop in the $data1 array and perform next actions
b. implode the array and search with IN. Example:
$commaSeparated = implode(",", $data1);
$results2=mysql_query('SELECT * FROM searchengine WHERE id IN ('.$commaSeparated.'));
mads.ohm is correct about combining the two queries into a single query.
As for your problem with only getting one return value, your while loop is just overwriting the contents of $data2 each time through.
You could write something like this instead:
$i = 0;
$data2 = array();
while ($row = mysql_fetch_array($results2)) {
$data2[$i] = $row;
$i++;
}
In this case, $data2 is declared as an array, and each iteration of the while loop adds a row from the database to the array.

Categories