how to get values of array out - php

I have this array
$pv->orderRecordsArray = array();
foreach($order->records as $i=>$orderRecord){
$pv->orderRecordsArray[] = $orderRecord->orderRecordID;
}
// print_r($pv->orderRecordsArray) for example
// shows Array ( [0] => 46839 [1] => 46840 [2] => 46841 )
I need to use the array values from above in my sql statement below.
$sql = "
SELECT
*
FROM
table1
WHERE
orderRecordID IN (46741, 46742)
";
so infront of IN I want $pv->orderRecordsArray results.
thanks

You can use implode to generate such a list:
$sql = "SELECT *
FROM table1
WHERE orderRecordID IN (" . implode(', ', $pv->orderRecordsArray) . ")";
But you should also consider a subquery or Join of your tables.

$sql = 'SELECT *
FROM table1
WHERE orderRecordID IN ('.implode(',',$pv->orderRecordsArray).')';

Related

Constructing mysql select from $_POST array

This is the $_POST array from my form.
Array ( [prescribedid] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 13 )
I want to create a select for any of items in the Array. I have written this, which produces the proper SELECT, but the if() to eliminate a trailing OR makes it clunky.
$query = "SELECT * ";
$query .= "FROM prescribed WHERE ";
for($i=0; $i<count($_POST["prescribedid"]); $i++) {
$query .= "prescribedid={$_POST['prescribedid'][$i]} ";
if($i < (count($_POST["prescribedid"])-1)) {
$query .= "OR ";
}
}
It produces this:
SELECT * FROM prescribed WHERE prescribedid=1 OR prescribedid=2 OR prescribedid=3 OR prescribedid=9 OR prescribedid=13
Is there another way to group the SELECTS or write the FOR() to make it cleaner, i.e. without the last IF().
$values=implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($values)";
Sanitization is on you :)
Hi You can Use In condition. use imploade function to find comma seoarated values
$data = array('prescribedid'=>array(1,2,3,9,14));
$query = 'SELECT * FROM prescribed WHERE prescribedid IN (';
$query .= implode(',',$data['prescribedid']).')';
echo $query ;
Output
SELECT * FROM prescribed WHERE prescribedid IN (1,2,3,9,14)
Use MySQL IN clause
$ids = implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($ids)";
You can simply use IN clause here.
Refer to MySQL IN clause
$query = "SELECT * FROM prescribed WHERE prescribedid IN ".implode(',', $_POST["prescribedid"]);

Make SQL selection from nested arrays

I am trying to make a selection based on a nested array I get from a prior selection.
Here is where I make my first selection:
$coursequery = "
SELECT
courseID
FROM enrollments
WHERE
studentID = '$userid'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
$_SESSION['studentcourses'] = $rows;
This gets all the courseID's in the following format:
Array ( [0] => Array ( [courseID] => 6 ) [1] => Array ( [courseID] => 7 ) )
and I want to be able to access these ID's for selecting information from a different table. I've started by trying to use a for loop to grab all the "course information" depending on the ID.
for($i = 0; $i < $count; $i++) {
$coursequery = "
SELECT
*
FROM courses
WHERE courseID = '$studentcourses[$i]'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetchAll();
$_SESSION['studentcourseinfo'] = $row;
}
Any help would be greatly appreciated in accomplishing this!
You can accomplish this with one SQL query thus eliminating all these loops
SELECT
*
FROM courses
INNER JOIN enrollments ON
enrollments.courseID = courses.courseID
AND enrollments.studentID = '$userid'
WHERE 1
you can use same array in query, can use implode function
$coursequery = "SELECT * FROM courses
WHERE courseID IN (" . implode(",", $studentcourses) . ");";
As long as you change the output format
Array (6, 7)
where 6 and 7 would be the id of the courses
Also in you code have mistake in rewrite var $_SESSION['studentcourseinfo'] = $row; these overwriting the same variable at a time

splitting an array with single key and string value into an array with multiple keys and values

I have a table which stores the courses registered by students during a semester and session. I populated it with course-codes for a particular student. Here is the function that fetches the course-code below:
function get_course_code(){
global $connection;
$query = "SELECT DISTINCT course_code ";
$query .= "FROM tbl_registered_courses_400 ";
$query .= "WHERE matric_no = '03/55ec101' LIMIT 10";
$course_code_set = mysql_query($query, $connection);
confirm_query($course_code_set);
return $course_code_set;
}
When I called the function in my main page. It returned the following result
$courseCode = get_course_code();
$courseFilter = '';
while ($courseList = mysql_fetch_array($courseCode)){
$courseList['course_code'];
$courseFilter .= "\""."{$courseList['course_code']}"."\",";
$courseFilter;
}
$course = array($courseFilter);
print_r($course);
Array ( [0] => "PHY 432","CSC 491","CHM 401","CHM 402","MAT 451","MAT 452","CSC 423","BLY 401", )
I want to split the $course array into an array that will have the values of the string in the above to read
array(
[0] => PHY 432
[1] => CSC 491
[2] => CHM 401
[3] => CHM 402
.
.
.
e.t.c
)
The string data in the $course array is from the course_code column in the database.
My intention is to use the results of the new array to form a row in the database that will hold the results of each matric_no for different courses done for the semester/session. I would appreciate any help I can get to get this done.
create the array and then assign the values to that array.
$courseCode = get_course_code();
$course = array();
while ($courseList = mysql_fetch_array($courseCode)){
$course[] = $courseList['course_code'];
}
print_r($course);

mysql SELECT a whole column or cycle through all IDs

I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";

Mysql Query from an array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
MySQL query using an array
How to use an array of values from PHP in the 'IN' clause of mysql query?
from a Post form i have an array like that
Array
(
[userid] => Array
(
[0] => 4e8329e97231c
[1] => 4e64b47849318
[2] => 4e4e415a30000
)
)
i am little struggle to retrieve the users data from mysql from this array
that should be something like this :
SELECT * FROM user_detail WHERE user_id='4e64b47849318' OR user_id='4e8329e97231c' OR user_id='4e4e415a30000'
Use implode().
$yourArray = array_map("mysql_real_escape_string", $yourArray);
$query = "SELECT * FROM user_detail WHERE user_id='";
$query .= implode($yourArray, "' OR user_id='");
$query .= "'";
Or indeed, use the SQL IN keyword:
$yourArray = array_map("mysql_real_escape_string", $yourArray);
$query = "SELECT * FROM user_detail WHERE user_id IN ('";
$query .= implode($yourArray, "','");
$query .= "')";
$clean_userid = array_map('mysql_real_escape_string', $arr['userid'])
$str_user_id = "'" . implode("', '", $clean_userid ) . "'";
$sql = "SELECT * FROM user_detail WHERE user_id IN ( $str_user_id )";
You can use the MySQL IN operator nicely here, it works like "OR" but you can essentially give it a list.
$user_id_string = implode(',', $array['userid']);
You now have a comma separated string of your user_id's.
Now query something like:
SELECT * FROM user_detail WHERE user_id IN ($user_id_string);
$criteria = "'".implode("','",$userID)."'";
$sql = "select * from user_detail where user_id in ($criteria)";
$query="SELECT * FROM user_detail
WHERE user_id='".(intval) $array['userid'][0]."'
OR user_id='".(intval) $array['userid'][1]."'
OR user_id='".(intval) $array['userid'][2]."'";
You could try
"SELECT * FROM user_detail
WHERE user_id IN ('". implode("','", $array['userid'])."')"

Categories