I am adding a database to my event website with the webpages mon-sun each with its own SQL table. Each page can have any number of events. The table has 6 columns (ID,name,club,location,host,description). Currently I am using a tiresome method to call the data. I'm looking for an addition to my code so that calling the data is a bit more automated. My code so far.
<?php
$dbhost = 'localhost';
$dbname = 'events';
$dbuser = 'max';
$dbpass = '';
$appname = "Dundaah";
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);
function queryMysql($query)
{
global $connection;
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
}
$row = queryMysql("SELECT * FROM monday WHERE ID=1");
$one = $row->fetch_array(MYSQLI_ASSOC);
$row2 = queryMysql("SELECT * FROM monday WHERE ID=2");
$two = $row2->fetch_array(MYSQLI_ASSOC);
?>
Then to call for the first event I use.
<?php echo ucwords(strtolower($one['name']));?>
<?php echo ucwords(strtolower($one['club']));?>
<?php echo ucwords(strtolower($one['location']));?>
<?php echo ucwords(strtolower($one['host']));?>
<?php echo ucwords(strtolower($one['description']));?>
For the second event I use the same method but I'm looking for a way to loop through instead of declaring a new fetch array every time. Thank you.
Something along these lines may help.
First you create an array that contains the days of the week, then you loop through the array in a foreach and perform a query on the database for each day. In this example I'm storing the results for each day in a single array with the Day name as the key (untested but hopefully it'll help).
$dbhost = 'localhost';
$dbname = 'events';
$dbuser = 'max';
$dbpass = '';
$appname = "Dundaah";
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);
$daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
$resultsFromDB = [];
foreach ($daysOfTheWeek as $day) {
$query = "SELECT * FROM events WHERE day = '$day'";
$result = $connection->query($query);
$resultsFromDB[$day] = $result->fetch_all(MYSQLI_ASSOC);
}
// Display the results in a page
echo "<h1>Events</h1>";
foreach ($daysOfTheWeek as $day) {
echo "<h2>$day</h2>";
foreach ($resultsFromDB[$day] as $event) {
echo $event['name'];
}
}
You can use IN sql statement get rows with several different ids.
$row = queryMysql("SELECT * FROM monday WHERE ID IN (1, 2) ORDER BY ID ASC");
$one = $row->fetch_assoc(); // same as fetch_array( MYSQLI_ASSOC )
$two = $row2->fetch_assoc();
ORDER BY ID ASC required if you want to get first row as row with id=1 (least ID), without it mysql (as well as any other db) doesn't guarantee any order.
If you need (for example) all rows with id less then 1000. You can use "less or equeal" comparison and save all rows into array.
$result = queryMysql("SELECT * FROM monday WHERE ID<=1000 ORDER BY ID ASC");
$all_rows = $result->fetch_all( MYSQLI_ASSOC );
// then
//$one = $all_rows[0];
//$two = $all_rows[1];
Also you don't need to materialize all results immediatly. Mysqli_result is traversable object. You can write foreach( $result as $row ) and get all rows any time. During foreach all raws will be fetched as assoc array.
Got it.
$query = "SELECT * FROM events WHERE day='mon'";
$result = $conn->query($query);
if (!$result) die($conn->error);
$rows = $result->num_rows;
$j = 0;
$name_array='';
$club_array='';
$location_array='';
$host_array='';
$description_array='';
while ($j < $rows )
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_ASSOC);
$event_name = $row['name'];
$event_club = $row['club'];
$event_location = $row['location'];
$event_host = $row['host'];
$event_description = $row['description'];
$name_array[]=$event_name;
$club_array[]=$event_club;
$location_array[]=$event_location;
$host_array[]=$event_host;
$description_array[]=$event_description;
++$j;
}
echo $name_array[0];
echo $club_array[0];
echo $location_array[0];
echo $host_array[0];
echo $description_array[0];
Related
I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
This is my database of mysql on the web
This is my database on the web
This is the PHP file to access the database to get a JSON file, first I select all the "category" cell in the table, then loop through the category, and then loop through the other columns of a category, and assign to an array of $data2, after that assign $data2 and category to br an array of $data, which is the json I want to display.
<?php
header("Access-Control-Allow-Origin: *");
$user = "u348833238_rest"; /* User */
$password = "a!23286029"; /* Password */
$dbname = "u348833238_rest"; /* Database name */
$host = "localhost";
$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
// $sel = mysqli_query($con,"select * from restaurant");
// $data = array();
// while ($row = mysqli_fetch_array($sel)) {
// $data[] = array("dishes" => ["name"=>$row['food'], "price"=>$row['price']] , "category"=>$row['category']);
// }
// echo json_encode($data);
$sel = mysqli_query($con,"select distinct category from restaurant");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$c = $row['category'];
$sel2 = mysqli_query($con,"select * from restaurant where category = $c ");
$data2 = array();
while ($row2 = mysqli_fetch_array($sel2)){
$data2[] = array("name"=>$row2['food'], "price"=>$row2['price']);
}
// echo $data2;
$data[] = array("category"=>$row['category'], "dishes"=>$data2);
}
// echo $data;
echo json_encode($data);
?>
How the JSON is not displayed properly as the array of property "dishes" is empty as below:
the array is empty
I’d recommend turning errors on so you can see where the problem is.
At a guess it’s here:
select * from restaurant where category = $c
Should be:
select * from restaurant where category = '$c'
Here I have a php code that connects to a database, selects a row by id and creates an associative array from this row using a while loop. Do I have to write this code over and over again to create arrays from other rows by id? Maybe there is a chance to simplify this php code somehow? Please look at my code. BTW I am new in php...
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
$sql1 = "SELECT * FROM pics WHERE id = 1;";
$sql2 = "SELECT * FROM pics WHERE id = 2;";
$sql3 = "SELECT * FROM pics WHERE id = 3;";
$sql4 = "SELECT * FROM pics WHERE id = 4;";
$sql5 = "SELECT * FROM pics WHERE id = 5;";
$sql6 = "SELECT * FROM pics WHERE id = 6;";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$result3 = $conn->query($sql3);
$result4 = $conn->query($sql4);
$result5 = $conn->query($sql5);
$result6 = $conn->query($sql6);
while($row1 = $result1->fetch_assoc()) {
$bcgrnd = $row1["link"];
}
while($row2 = $result2->fetch_assoc()) {
$recipes = $row2["link"];
}
while($row3 = $result3->fetch_assoc()) {
$header = $row3["link"];
}
while($row4 = $result4->fetch_assoc()) {
$menu = $row4["link"];
}
while($row5 = $result5->fetch_assoc()) {
$beauty = $row5["link"];
}
while($row6 = $result6->fetch_assoc()) {
$kids = $row6["link"];
}
?>
You can do this in one query:
$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);
And then you can loop over all results like this:
$data = array();
while ($row = $result->fetch_assoc()) {
$id = $row["id"];
$link = $row["link"];
$data[$id]["link"] = $link;
// add more fields if you want
}
To access for example the link of ID 1, just do:
$data[1]["link"];
You can write one or two simple functions for this. Moreover, please note that your code is vulnerable to SQL Injection. Here is an example how you can achieve this with some simple functions:
<?php
function DB() {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
return new mysqli($dbhost, $dbuser, $dbpass,$db);
}
function query($id) {
$query = "SELECT * FROM `pics` WHERE `id` = $id";
return DB()->query($query);
}
$result = query(1); // will fetch records for ID 1
while($row = $result->fetch_assoc()) {
$bcgrnd = $row["link"];
}
$result = query(2); // will fetch records for ID 2
while($row = $result->fetch_assoc()) {
$bcgrnd = $row["link"];
}
?>
By adapting this approach, you can fetch data for a specific ID. If you don't like this solution, consider using MySQL IN clause.
Try this.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$bcgrnd[$row["id"]][] = $row["link"];
}
?>
Why not try a Query and Limit it to 6 results, it takes up less resources just pulling 6 results:
SELECT * FROM `pics` ORDER BY `[PRIMARY KEY]` LIMIT 6
MySQL in() function finds a match in the given arguments, you can use it
select pics where id IN(1,2,3,4,5,6)
I've tried for a couple of days to get all of the data from a MySQL column and put it inside an array, formatted in the following way:
$aSpam= array
( '.info'=> 'i'
, 'anal'=> 'i'
, 'anus'=> 'i'
, 'arse'=> 'i'
)
I've managed to echo it out formatted properly as you can see here: http://www.yourgrumble.com/phpbbforum/getSpam.php
with the following PHP code:
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT `SpamWord` FROM spamWords";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0;
while($row = $result->fetch_assoc()) {
if($counter){
echo ", '" . $row["SpamWord"]. "'=> 'i'";
$counter++;
} else {
echo "'" . $row["SpamWord"]. "'=> 'i'";
$counter++;
}
}
} else {
echo "Error!";
}
$conn->close();
?>
I've read and tried more than 10 solutions found in the web and here at stackoverflow, however none of them worked. I've really got desperate and I cannot get through this without your help guys.
Edit
For example I tried with this solution, but it didn't work:
while ($row = mysql_fetch_array($result))
{
$new_array[$row['id']]['SpamWord'] = $row['SpamWord'];
}
foreach($new_array as $array)
{
echo $array['SpamWord'].'<br />';
}
Thank you all in advance,
Denis Saidov
Try like below:-
$sql = "SELECT `SpamWord` FROM spamWords";
$result = mysqli_query($conn ,$sql) or die(mysqli_error($conn));
$resultArray = array(); // create an array
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$resultArray[$row["SpamWord"]] = 'i'; // assing value
}
} else {
echo "Error!";
}
echo "<pre/>";print_r($resultArray); // print array
$conn->close();
Note: Here you will get your original array containing all SpamWord values comes from database.thanks
PHP array's are like dictionnaries (a list of key/value pairs)
First, before your loop, create your array empty:
$new_array = Array();
while...
Then for each column, you append the column value as a new key for the array
$new_array[$row['SpamWord']] = "i";
As in your example, I put "i" as the value for each array's row.
Why does this only print the sites specific content under the first site, and doesn't do it for the other 2?
<?php
echo 'NPSIN Data will be here soon!';
// connect to DB
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to DB');
$dbname = 'npsin';
mysql_select_db($dbname);
// get number of sites
$query = 'select count(*) from sites';
$result = mysql_query($query) or die ('Query failed: ' . mysql_error());
$resultArray = mysql_fetch_array($result);
$numSites = $resultArray[0];
echo "<br><br>";
// get all sites
$query = 'select site_name from sites';
$result = mysql_query($query);
// get site content
$query2 = 'select content_name, site_id from content';
$result2 = mysql_query($query2);
// get site files
// print info
$count = 1;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "Site $count: ";
echo "$row[0]";
echo "<br>";
$contentCount = 1;
while ($row2 = mysql_fetch_array($result2, MYSQL_NUM)) {
$id = $row2[1];
if ($id == ($count - 1)) {
echo "Content $contentCount: ";
echo "$row2[0]";
echo "<br>";
}
$contentCount++;
}
$count++;
}
?>
The problem is that you assume that once your finished looking for the row with the same id as the site row, that it'll reset the $result2 query to the beginning. This means that after you find your first row (unless you were to sort the two queries), that the second pass of the while loop wouldn't have any results left. You should consider caching the inner while loop first and then using an array lookup to get the value.
An even better solution would involve a join from sites to content which wouldn't require this complex matching process. Joins are a VERY important part of SQL, I highly suggest learning how to use them. http://dev.mysql.com/doc/refman/5.0/en/join.html