I have two arrays in my php that I want to print. I want them to be concatenated but I don't know how. The array for the $names prints but the description array "$desc" does not. is there any way to print both together?
$query = "SELECT eName FROM Events";
$query2 = "SELECT eDescription FROM Events";
$result = mysql_query($query);
$result2 = mysql_query($query2);
$names = array();
$desc = array();
echo "hello there people!" . $query . " ".$result;
for($i=0; $i<sizeof($result); $i++){
echo $result[$i] ."\n" . $result2[$i];
}
while($entry = mysql_fetch_row($result)){
$names[] = $entry[0];
}
while($entry2 = mysql_fetch_row($result2)){
$desc[] = $entry2[0];
}
echo "Which Event would you like to see?<br>";
$stop = count($names);
//echo $stop . "\n";
$i = 0;
print_r($names);
print_r($desc);
foreach($names as $value){
echo $value . " " . $desc[i] ."<br>";
$i++;
}
Why are you doing two queries to get data from the same source?
$sql = mysql_query("select `eName`, `eDescription` from `Events`");
while($row = mysql_fetch_assoc($sql)) {
echo $row['eName']." ".$row['eDescription']."<br />";
}
Much simpler.
Try this:
foreach($names as $key => $value){
echo $value . " " . $desc[$key] ."<br />";
}
As long as the array $key match, the information will be printed together.
Related
I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
I have the following working array of an array in PHP:
$explore1 = array
(
array("a.html", "A"),
array("b.html", "B"),
array("c","C")
);
$arrlength = count($explore1);
for($x = 0; $x < $arrlength; $x++) {
echo '<li>'.$explore1[$x][1].'</li>';
} }
I want to populate the explore1 array from SQL. If i simply change the code like below it has errors but I don't know what I'm suppose to do instead?
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$explore1 = array //IT DOESN'T LIKE THIS LINE
(
while($row = $result->fetch_assoc()) {
// BUILD SAME LINES AS ABOVE WITH ECHO
echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
}
);
Can anybody help?
Either you don't need $explore1 at all:
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
echo '<li>'.$row["name"].'</li>';
}
}
or if you need you can fetch_all():
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$explore1=$result->fetch_all(MYSQLI_ASSOC);
foreach($explore1 as $row ) {
//echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
echo '<li>'.$row["name"].'</li>';
}
}
Please learn some php basics.
Defining an array of arrays is something like:
$explore1 = array();
while($row = $result->fetch_assoc()) {
$explore1[] = array($row["url"], $row["name"]);
}
You must populate the array inside the loop:
while($row = $result->fetch_assoc()) {
$explore1[$row["url"]] = $row["name"];
}
I'm tryinh to encode all rows in table to JSON but it seems to miss the first one.
$sql = "SELECT * FROM NewsStream";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "echo: " . $row["id"]. " " . $row["title"]. " " . $row["content"]. "<br />";
echo "JSON: " . json_encode($row). "<br />";
}
}
The result is:
echo: 0 title content
JSON:
echo: 1 abc efg
JSON: {"id":"1","title":"abc","content":"efg","type":"11","author":"12","preview":"13","src":"14","date":"2015-02-20"}
echo: 2 4563 456465
JSON: {"id":"2","title":"4563","content":"456465","type":"54","author":"5463","preview":"6454","src":"456","date":"2015-02-12"}
Why the first "JSON: " is missing while echoing results are right?
try this one:
$sql = "SELECT * FROM NewsStream";
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r;
}
print json_encode($rows)
Try this
$return_arr = array();
$fetch = mysql_query("SELECT * FROM NewsStream");
while ($row = mysql_fetch_assoc($fetch)) {
$data=array();
foreach ($row as $key => $value) {
$data[$key]=$value;
}
$return_arr[] = $data;
}
echo json_encode($return_arr);
How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.
I have the following PHP code:
echo "var s1 = [";
$count = 0;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count++ > 0) echo ", ";
echo $row['OrdersBal'];
}
echo "];\n";
echo "var ticks = [";
$count2 = 0;
while($row2 = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count2++ > 0) echo ", ";
echo "'" . $row2['CardName'] . "'";
}
echo "];\n";
It's currently outputting:
var s1 = [37966.550000, 19876.170000, 17314.580000, 15614.410000, 7575.000000];
var ticks = [];
But I want it to output:
var s1 = [37966.550000, 19876.170000, 17314.580000, 15614.410000, 7575.000000];
var ticks = ['Parameter Technology', 'Earthshaker Corporation', 'Microchips', 'Mashina Corporation', 'SG Electronics'];
If I move the second while statement so that it occurs first then that statement will output correctly. This has lead me to believe that I can't execute two while statements in a row in this fashion, but I'm not sure what my alternatives are. Thanks for any help!
Use variables to store text during loop and then print them out:
$count = 0;
$orders = "";
$cardNames = "";
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count++ > 0)
{
$orders .= ", ";
$cardNames .= ", ";
}
$orders .= $row['OrdersBal'];
$cardNames .= $row['CardName'];
}
echo "var s1 = [" . $orders . "];\n";
echo "var ticks = [" . $cardNames . "];\n";