This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 6 months ago.
I need to select ids from database with arrays.
my english not good. I think the best way to show my codes
the form result print_r($malayalam); like this Array ( [0] => helo [1] => hi[2] => how)
I need to select its ids from table. my code is not correct. any way let me show you here
$results=mysql_query("SELECT ml_id FROM ml_table WHERE word = '$malayalam'");
$numrows=mysql_num_rows($results);
if($numrows!=0){
$ml_row = mysql_fetch_array($results);
$ml_id = $ml_row['ml_id'] ;
echo "Malayalam ID " . $ml_id . "<br />";
}
I need to add all my result in to another array.
is that possible ?
if u have any idea could you answer to me please
If I understood properly, the following is what you need
$results=mysql_query("SELECT * FROM ml_table WHERE word = '$malayalam'");
if(mysql_num_rows($results)>0){
$newArray = array(); //Create a new array
while($ml_row = mysql_fetch_array($results)) {
$ml_id = $ml_row['ml_id'] ;
$newArray[$ml_id] = $ml_row;
echo "Malayalam ID " . $ml_id . "<br />";
}
//$newArray is your new array accesible from id
}
You should write something like this:
$ids = array();
$in = '"' . implode('","', array_map('mysql_real_escape_string', $malayalam)) . '"';
$result = mysql_query('SELECT id FROM ml_table WHERE word IN(' . $in . ')');
while($row = mysql_fetch_assoc($result)) {
$ids[] = $row['id'];
}
$anotherArray = array_merge($ids, $anotherArray);
OR
$anotherArray += $ids;
$i=0;
foreach($malayalam as $key=>$value)
{
$results=mysql_query("SELECT * FROM ml_table WHERE word = '$value'");
$numrows=mysql_num_rows($results);
if($numrows!=0)
{
$ml_row = mysql_fetch_array($results);
$ml_id = $ml_row['ml_id'] ;
$ml_ad[$i]=$ml_id;
echo "Malayalam ID " . $ml_id . "<br />";
$i++;
}
}
Now when you printr($ml_ad); it will show all your id's in an array.
finally fainally found solution with the help of answers
$rArray = mysql_query("SELECT ml_id FROM ml_table WHERE word IN ('".implode("', '", $malayalam)."')");
if(mysql_num_rows($rArray)>0){
$temp_rows = array();
while(($row = mysql_fetch_array($rArray))) {
$temp_rows[] = $row['ml_id'];
}
}
the result of print_r($temp_rows) coming like this Array ( [0] => 123 [1] => 234 [2] => 312)
thank to all
Related
this is my code :
<?php
$sss = "SELECT tanggal_awal FROM libur_nasional GROUP BY tanggal_awal ASC";
$qqq = mysqli_query($konek,$sss);
$arr = array();
while ( $tam = mysqli_fetch_array($qqq)) {
$date = $tam['tanggal_awal'];
$reformat_date = date("n-j-Y", strtotime($date));
$arr[] = $reformat_date;
}
$array_date = implode(",", $arr);
?>
> output : 8-9-2018,8-10-2018,8-17-2018
> output i want to is : "8-9-2018", "8-10-2018", "8-17-2018"
could someone help me to get the output i want, thank before.
You can make your code a bit shorter:
$sss = "SELECT tanggal_awal FROM libur_nasional GROUP BY tanggal_awal ASC";
$qqq = mysqli_query($konek,$sss);
while ( $tam = mysqli_fetch_array($qqq)) {
$arr[] = date("n-j-Y", strtotime($tam['tanggal_awal']));
}
$array_date = '"' . implode('", ', $arr) . '"';
In php you don't need to declare an array before pushing values to it.
Your $date variable is not needed as it's just a copy of the $tam['tanggal_awal'] value.
$reformat_date is also not needed as you can place it in the array directly.
The imploding is what is placed between the items, by having ", there you just need to add a " at each end of the string.
$arr=['8-9-2018','8-10-2018','8-17-2018'];
$array_date = '"'.implode('", "', $arr) . '"';
echo $array_date;
Output ---> "8-9-2018", "8-10-2018", "8-17-2018"
Try to implode your array like this.
I have the following multidimensional array, generated after some database Selects:
<?php
$array = array (
array("X"=>500, Y="400"),
array("X"=>234, Y="347"),
array("X"=>845, Y="345"),
array("X"=>264, Y="916")
);
?>
Now I need to do a select in a table where BOTH field X and Y are in the array. How to do that? Like:
SELECT FROM table WHERE
(X=500 AND Y=400) OR
(X=234 AND Y=347) OR
(X=845 AND Y=345) OR
(X=264 AND Y=916)
;
I can only find solutions here on StackOverflow for a single item in a query, but not for two values in a multidimensional array that needs to be exactly the same. Thank you!
If I understood, you need to read your array and pass it to your SQL.
Something like:
<?php
$where = null;
foreach ($array as $a)
{
if (is_null($where))
{
$where = " WHERE (X = " . $a['X'] . " AND Y = " . $a['Y'] . ")";
}else
{
$where .= " OR (X = " . $a['X'] . " AND Y = " . $a['Y'] . ")";
}
}
$sql = "SELECT * FROM table " . $where;
?>
Hope it helps.
Hi I have this array called $allextensionsforque. See print_r below.
Array ( [0] => Local/101#from-queue/n,0 [data] => Local/101#from-queue/n,0 )
I'm trying a foreach like below but its not showing any data on the echo. Can anyone help?
$allextensionsforqueu = mysqli_query($conqueue,"SELECT data FROM queues_details WHERE id = '1' AND keyword ='member'");
$allextensionsforque = mysqli_fetch_array($allextensionsforqueu);
$foo = "";
foreach ($allextensionsforque as $extensionrow)
{
$extensionrowstriped = substr($extensionrow['data'],6,3);
$foo = "' " . $extensionrowstriped . " ' ,";
}
echo $foo;
You don't have an array in $extensionrow, since it's only an one dimensional array. So you just need to replace $extensionrowstriped = substr($extensionrow['data'],6,3); with $extensionrowstriped = substr($extensionrow,6,3);.
Check for errors using mysqli_error(). Here is a simple approach, but you may want to improve it for production use:
$allextensionsforqueu = mysqli_query($conqueue,"...") or die(mysqli_error($conqueue));
Next, append your data to $foo instead of overwritting it in each loop:
$foo .= "' " . $extensionrowstriped . " ' ,";
Finally, verify that $extensionrow contains the data that you expect. substr() will return false if a match is not found.
I´m trying using php to generate a set of "{URL.callback}" to use in javascript. By using database. Here is my code:
$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";
$result=mysql_db_query($dbname,$sql);
echo $_GET["callback"] . "({ t:\"$t\", r:[";
while ( $rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
echo "" ."\"$keywords\"".","." ";
}
echo"] })";
This is the code it returns:
({ t:"", r:["example1", "example2", "example3",] })
Everything seemed to be correct except the (,) in the end (after "example3") that I want to get rid. because it´s not correct and can not be use with that.
The question is: How to generate it correctly ? How to get rid the last (,) ?
Instead of generating the JSON yourself use json_encode to do the heavy lifting for you.
$keywords = array ();
while ( $rs=mysql_fetch_array($result)) {
$keywords[] = $rs['keywords'];
}
echo json_encode ($keywords);
Preferred solution
Though if you plan on using json_encode append $keywords to your other set of data and use json_encode on the whole structure.
$json_data = array (
't' => '',
'r' => array ()
);
while ( $rs=mysql_fetch_array($result)) {
$json_data['r'][] = $rs['keywords'];
}
echo "(".json_encode ($json_data).")";
If you'd like to do it yourself there are a few (rather clean) options available, see the snippets below.
Append all retrieved keywords to an array and use join with ',' as delimiter to form a string after your while loop
$keyword_array = array ();
while ($rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
$keyword_array = "\"$keywords\"";
}
echo join (', ', $keywords);
Use mysql_num_rows before your while loop to get the number of rows in $result, and don't append a , when you are processing the last element.
$n_rows = mysql_num_rows ($result);
for ($i =1; $rs = mysql_fetch_array ($result); ++$i) {
$keywords=$rs[keywords];
echo "\"$keywords\"";
if ($i != $n_rows)
echo ", ";
}
Try this:
$output = '';
while ( $rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
$output .= "" ."\"$keywords\"".","." ";
}
$output = substr($output, 0, -2);
echo $output;
Solution
Create data structure (multi-dimensional array) within PHP and let json_encode() generate JS data structure.
Example
It could look like this:
$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";
$result=mysql_db_query($dbname,$sql);
$data = array(
't' => $t,
'r' => array(),
);
while ( $rs=mysql_fetch_array($result)) {
$data['r'][] = $rs['keywords'];
};
and then display it like that:
echo $_GET["callback"].'('.json_encode($data).');';
Hope this works for you
$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";
$result=mysql_db_query($dbname,$sql);
echo $_GET["callback"] . "({ t:\"$t\", r:[";
$keywords_print = array();
while ( $rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
$keywords_print[] = "\"$keywords\"";
}
echo implode(",",$keywords_print);
echo"] })";
I think the cleanest way, is to create an array of elements, then implode them with a , as separator.
// added initial `"`
echo $_GET["callback"] . "({ t:\"$t\", r:[\"";
while ( $rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
$arr[] = $keywords;
}
echo implode('", "', $arr);
// added closing `"`
echo "\"] })";
I am attempting to generate a weekly email to users of my site that lists locations that have added new information. When someone adds information, a table receives two numbers, one for the state and the second for the county. The first step of my cron job is to take the numbers and convert them to county, state format (Alameda, California for example). At the end of each conversion I added a | to be used as a delimiter. This part works perfectly. Next I loop through each user to send this information via email but this part does not work. What I end up with is the word array instead of my county, state format. What am I missing?
This is the code that performs the 1st step, which works just fine:
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
$statename = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
$countyname = $county['Name'];
}
$locations = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "$countyname, $statename ". '</a>' . "|";
$i = $i + 1;
}
This is the code that I am using to explode the array into the county, state format, which does not function properly. Instead I get the word array.
$locals = explode("|", $locations);
$locals is used in the email message as the list of new information. Please point me in the right direction. Thanks
explode will give you array
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
so when you use explode function, it will explode string in to array
in your case .. write
$locals = explode("|", $locations);
echo "<pre>";print_r($locals);echo "</pre>";
and you will have exact idea and it will solve your problem
First, what is the purpose of $i?
Second, I think you want to concatenate $locations:
// This overwrites the variable - this is what you are doing
// at the end $locations will be the one single last link
$locations = '<a href="ht
// This adds to / concatenates - giving you a long strong of many links
$locations .= '<a href="ht
// ^ Note the period.
Third, explode does take a string and turns it into an array.
If you're making a long string, why would you want to explode it back into the parts you constructed it from?
I would suggest storing your states, countys, and constructed links in arrays. Then you can use the contents of those arrays at will to create your emails.
To look at what's in an array use print_r() or var_dump(). You can loop over arrays with foreach().
<?php
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
// There had better only be ONE statename per SID or you lose info!
$user_array[$i]['statename'] = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
// There had better only be ONE countyname per CID or you lose info!
$user_array[$i]['countyname'] = $county['Name'];
}
$user_array[$i]['link'] = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "{$user_array[$i]['countyname']}, {$user_array[$i]['statename']} ". '</a>';
++$i; // add one to i
}
// Show the arrays:
echo "<pre>";
print_r($user_array);
echo "</pre>";
?>
The above gives you an array like
Array
(
[0] => Array
(
[statename] => CA
[countyname] => San Bernardino
[link] => <a href="blah...
)
[1] => Array
(
[statename] => OR
[countyname] => Multnomah
[link] => <a href="yada...
)
)
To use the array just do
foreach ($user_array as $single_user_item) {
echo $single_user_item['link'];
}