build an array of an array from SQL query with php - php

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"];
}

Related

Count multiple columns from different tables php

I'm trying to count two different tables but it's not working, and I cannot find out where the problem is, and how to implement it with PHP.
$sql = "SELECT COUNT(users.user_id) AS totalUsers FROM users, SELECT COUNT(bikes.bike_id) AS totalBikes FROM bikes";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<td><td>" . $row["totalUsers"] . "</td></tr>";
echo "<td><td>" . $row["totalBikes"] . "</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
Get the amounts from each table separately. Each SELECT is a unique resultset from your query, listing them with commas won't retrieve all data as you are expecting.
$result = $conn->query("SELECT COUNT(users.user_id) AS totalUsers FROM users");
$totalUsers = 0;
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$totalUsers = $row["totalUsers"];
}
$result = $conn->query("SELECT COUNT(bikes.bike_id) AS totalBikes FROM bikes");
$totalBikes = 0;
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$totalBikes = $row["totalBikes"];
}
$conn->close();
Then you can work with the values stored in $totalUsers and $totalBikes:
echo "<tr><td>" . $totalUsers . "</td></tr>";
echo "<tr><td>" . $totalBikes . "</td></tr>";

Search database using array and then echo/print result in foreach loop using PHP

I need to get variable code from URL so I $codes = $_GET['code']; (url example website.com/update?code[]=7291&code[]=9274&code[]=8264&) then I SELECT firstname FROM guests WHERE invitecode = $codes" then I output data and set as $relatives = $row["firstname"] and then later on in the file I need to echo/print print $relative.
Why is this not working for me?
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = $codes";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
Update:
So now using:
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ",";
if($thecodes != "")
{
$thecodes = trim($thecodes, ",");
$sql = "SELECT firstname FROM guests WHERE invitecode IN ($thecodes)";
$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
}
else
{
}
?>
It works but I would like to enter the foreach ($relatives as $relative) { echo $relative; }; into a value like this $message = $firstname . " " . $lastname . " will be coming to your event. " . ;.
In the end it would turn out something like this: $message = $firstname . " " . $lastname . " will be coming to your event. " . foreach ($relatives as $relative) { echo $relative . " "; };.
For some reason it won't work when I combine them.
Use the IN operator for this.
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ","; //Loop through making sure each is an int for security reasons (No sqli)
if($thecodes != "") //There is at least one code
{
$thecodes = trim($thecodes, ","); //Remove any additional commas
$sql = "SELECT firstname, lastname FROM guests WHERE invitecode IN ($thecodes)"; //Use the IN operator
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["firstname"] . " " . $row["lastname"] . "is coming to your event";
}
}
}
else //No codes to be queried
{
}
?>
Can this be a solution for you?
$relatives = array(); // declare array
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE ";
foreach ($codes as $code) $sql .= "invitecode = " . intval($code) . " OR ";
$sql .= "1=2"; // simple way to remove last OR or to make sql valid if there are no codes
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($relatives, $row["firstname"]);
}
}
foreach ($relatives as $relative) {
print $relative;
}
I think this will work...
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = '$codes'";
$result = mysqli_query($conn, $sql) or die('-1' . mysqli_error());
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo ($row['firstname']);
}
}

JSON encoding missing first row from MySQL

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);

PHP And JS Code Not Executed

i Have This PHP and JS Code on my web page.
<?php
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());;
$counter = 0;
// write the values from the database into the javascript array
echo "<script type='text/javascript'>";
echo "this.styleListArray = new Array();";
if ($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname'
$counter += 1;
}
}
echo("</script>");
?>
The Problem is that when i execute the page containing the code, a part of this code doesn't get executed and it just shows on the page as a simple text :
"); echo "this.styleListArray = new Array();"; if ($result) { while($row = mysql_fetch_array($result)) { echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname' $counter += 1; } } echo(""); ?>
I tried to figure it out, but i couldn't get it, if you can help brothers, that would be wonderful.
Try rewriting your code like this:
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());
$counter = 0;
// write the values from the database into the javascript array
echo <<<HTML
<script type='text/javascript'>
this.styleListArray = new Array();
HTML;
$strLine = '';
if ($result) {
while($row = mysql_fetch_array($result)) {
$strLine.= "this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';";
$counter += 1;
}
}
echo $strLine;
echo("</script>");
First of all change your queries to use mysqli or pdo connections
secondly try following code
$sql = 'SELECT URL FROM remontee_nlf ORDER BY URL ASC';
$res = mysql_query($sql, $con);
$rows = array();
while ($row = mysql_fetch_assoc($res))
$rows[] = $row['URL'];
$str = implode('", "', $rows);
$data = '["'.trim($str).'"]';
echo '<script type="text/javascript">';
echo "var data = $data;";
echo 'console.log(data)';
echo '</script>';
check you console log.
You have $result = mysql_query($query) or die (mysql_error());; change it to
$result = mysql_query($query) or die (mysql_error());
Also make sure $row['URL'] and $row['user_fname'] are available.

how to print out two arrays in php concatenating them

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.

Categories