I have a table "orders" which saves all the orders made on a website. It saves the data in the following way:
ID | Session_id | image | item | extra | customer_name
Sample date
12 | sdgfafjhsf | image1.jpg | coffee | milk | roger
13 | sdgfafjhsf | image1.jpg | muffin | jam | roger
14 | fjgjgsdfjg | image3.jpg | coffee | none | John
Currently I have the PHP accessing the database and spitting out all of the listings one by one.
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("store") or die(mysql_error()) ;
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM orders WHERE status ='ordered'") or die(mysql_error()); //Puts it into an array
while($info = mysql_fetch_array( $data ))
{
//Outputs the image and other data
Echo "$info[customer_name] <img src='cameras/$info[image]'/> : $info[item] with $info[extras] <br />";
}
I am ideally wanting the data to group by the session ID. So it prints out the name of the customer and the image once and then all of the items associated with it.
eg. Roger , coffee, milk, muffin, jam
Any ideas?
Thanks!
A simple way would be to order the SQL so that you get all entries from each session following each other, and just remember the last session id you fetched to tell if you should output the name and picture or not; here's some pseudo code to show what I mean;
$data =
mysql_query("SELECT * FROM orders WHERE status ='ordered' ORDER BY session_id")
or die(mysql_error());
$last_session_id = "**DUMMY**"; // Set a dummy value to not match the first row
while($info = mysql_fetch_array( $data ))
{
if($info['session_id'] != $last_session_id)
{
//Outputs the image and other data if a new session_id has been found
echo "$info[customer_name] <img src='cameras/$info[image]'/> : $info[item] with $info[extras] <br />";
$last_session_id = $info['session_id'];
} else {
// Same session_id as last row, skip name and picture
echo "$info[item] with $info[extras] <br />";
}
}
As a side note, the mysql_* database API is deprecated, you should look into using mysqli or pdo instead.
well try this..
SELECT Session_id,image,item,extra,customer_name FROM orders WHERE status='ordered' group by Session_id,image,item,extra,customer_name
Here you have to run two separate query. In first query you have to find all distinct customer name, better if you use customer id rather than customer name because id cannot be duplicate. Then after getting all customer who have ordered item, iterate them in loop and inside loop run another query to retrieve all orders of that customer by again customer id or by customer name.
In you while($info = mysql_fetch_array( $data ))-loop, where you print the output, you could add it to a standard array where the keys are the Session_ids.
Then you call echo $foo['sdgfafjhsf'] to get an array with db-entries which you can enumerate through print accordingly.
Related
I will start with saying I'm new to mysql and I haven't found any answer for my problem here, nor couldn't remake other examples by myself.
I have a table called "profiles" where I store my users, and one of the columns is "points" which stores integers.
I have a second table called "pointsCounter" with only one column "pointsTotal" (also integer) which stores only points from every user on site.
I would like to sum up every user "points" in "profiles" and store the result in "pointsTotal" in table "pointsCounter". I'm making the query using php to then echo the result to file that requests data with ajax.
Example:
profiles
id | points |
---------------------------
1 | 10 |
2 | 20 |
3 | 0 |
4 | 40 |
pointsCounter
pointsTotal |
--------------
70 |
This is my current not complete php code:
<?php
include 'db_connect.php';
$sql = "SELECT points FROM profiles";
$result = mysqli_query($mysqli, $sql); //$mysqli is my connection defined in db_connect
if (mysqli_num_rows($result) > 0){
$points = mysqli_fetch_assoc($result);
}
echo $points['pointsTotal'];
This is probably best handled as a query. Use the SUM() sql function to sum all the points together in the query, as "pointTotal". The rest of the code should work fine.
Try this:
$sql = "SELECT SUM(points) AS pointTotal
FROM profiles";
$result = mysqli_query($mysqli, $sql); //$mysqli is my connection defined in db_connect
if (mysqli_num_rows($result) > 0){
$points = mysqli_fetch_assoc($result);
}
echo $points['pointTotal'];
I've been messing around with PHP once again. I am trying to retrieve information from a specific Column. So for example I'll do
http://127.0.0.1:8002/api/galaxy/rgalaxy.php?api&Name=Hi
The Column looks like this.
+----------------+-------+
| Name | Data |
+----------------+-------+
--> | Hi | Grab | <--
| Medium product | 9.99 |
| Large product | 15.99 |
+----------------+-------+
And It'll retrieve this info Grab
So since I put in Hi As the Parameter, It'll retrieve Grab
I have no idea how to do that. Would anyone mind helping?
$query = "SELECT column_name FROM table_name WHERE other_column = 'value'";
replace "column_name", "table_name", "other_column" and "value" by desired.
To get your 'Name' value from url use $_GET['Name']
Firstly, open a connection to your database
$connection = mysqli_connect('localhost', 'db_username', 'db_password, 'db_name');
Then, use this connection to perform your query
Edit : to avoid SQL injection
<?php
$name = '';
if(isset($_GET['Name'])){
$name = $_GET['Name'];
}
$connection = mysqli_connect('localhost', 'root', '', 'ett');
$query = 'SELECT name FROM items WHERE name like ?';
$stmt = $connection->prepare($query);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$names_array = array();
while ($row = $result->fetch_assoc()) {
$names_array[] = $row;
}
Insert this Mysql query if you want only Data value as Grab
$name=$_GET['Name'];
$sql = "SELECT Data FROM YOUR_TABLE_NAME WHERE Name='.$name.' ";
and if you want to fetch more data like
| Hi | Grab |
| Medium product | 9.99 |
| Large product | 15.99 |
all then you need to add one more column who's value is common to all row and pass those column value to your url .
Your MySQL query will look something like this:
"SELECT * FROM your_table_name WHERE Name=$_GET['Name']"
Then you need to run the above query, and fetch it into a PHP variable and do whatever you want with that. I hope this helps you.
Part of a script I am writing requires me to know exactly how a result set gets it's information from a MYSQL query.
I have a standard result from an SQL query, which I then make a row array using fetch_array.
Whilst looping through this content let's say I delete one of the rows I find from the table. If I reset the pointer of the result back to the first, will I find that row again even though it no longer exists, find an empty row, or miss that row entirely?
In other words is the result asking MYSQL for each row as it needs it, or does it get the whole array in one go so it will not pickup on any changes to the table afterwards?
Cheers in advance
EDIT
$result = $conn->query("SELECT ID, value FROM table");
while($row=$result->fetch_array()){
if(x){
$conn->query("DELETE FROM table WHERE ID=$row['ID']");
mysqli_data_seek($result,0);
}
}
The question is will that deleted row be repeated after the reset, get skipped or return something else such as NULL?
No, it will not delete that row inside initial fetched result set.
But of course it will delete the row in your present table.
If you try to reset the pointer, the initial result set with that row still resides. Not unless you overwrite it with another one.
Consider this example. Lets say you have this inside your table:
+----+--------+
| id | value |
+----+--------+
| 1 | test1 |
| 2 | test2 |
| 5 | test5 |
+----+--------+
If you make this kind of operation:
$result = $conn->query('SELECT id, value FROM mytable'); // sample query
while($row = $result->fetch_assoc()) { // fetch all results
if($row['id'] == 5) { // some condition
$conn->query('DELETE FROM mytable WHERE id = 5'); // delete one row in table
}
}
$result->data_seek(0); // reset the pointer
while($row = $result->fetch_assoc()) { // fetch the same result set
echo $row['id'] . '<br/>';
}
It will delete that particular row in your table but not the one in the initial result.
At initial load, it will show:
1
2
5
If you refresh it, now 5 will be gone since its a new request and another result set called.
I have a mysql database of visitor IPs, and I'm trying to create an HTML table that shows how many of those IPs are from X country. I can get the script to show which country the visitor is from, but I cannot seem to find a way to show it in groups rather than line by line.
For example, currently I'm getting:
Country | Visitors
------------------
US | Array
UK | Array
UK | Array
UK | Array
US | Array
MX | Array
MX | Array
What I want is:
Country | Visitors
------------------
US | 2 Visitors
UK | 3 Visitors
MX | 2 Visitors
I've tried array_count_values, but it still lists every visitor by line and assigns a value of "Array" to every line.
The IPs are in a database and the script pulls the IPs and then assigns the IP a Country Code value based on the data in a separate file.
Here's what I hacked up with my amateur skills. If there's a better way to accomplish this, suggestions welcome!
require_once("geoip.inc");
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
include_once($_SERVER['DOCUMENT_ROOT'] . 'connect.php');
/* Performing SQL query */
$data = mysql_query("SELECT * FROM the_ips LIMIT 100")
or die(mysql_error());
echo "<table>";
echo "<td><strong>Country</strong></td><td><strong>Visitors</strong></td></tr>";
while($info = mysql_fetch_array( $data ))
{
$ip = $info['ip_address'];
$country_code = geoip_country_code_by_addr($gi, $ip);
$countrylist = array($country_code);
$frequency = array_count_values($countrylist);
echo "<tr><td style='width: 100px;'>".$country_code."</td><td style='width: 100px;'>".$frequency."</td></tr>";
}
echo "</table>";
geoip_close($gi);
SELECT
Count(Distinct country) As country_number
, country
FROM the_ips
GROUP BY country
LIMIT 100
try this for a start
For anyone else looking for the exact method to remove duplicate entries, here it is. Assuming that your duplicates are in the 'name' column. Just change the 'name' and 'id' to your tables respective column names.
// Select duplicate entries
$result = mysql_query("SELECT id, name
FROM tble_name
GROUP BY name
HAVING COUNT(*) > 1");
// Loop through the results
while($rows=mysql_fetch_assoc($result)){
// Delete each row by id
mysql_query("DELETE FROM tble_name
WHERE id = ".$rows['id']."");
}
Note: This will remove the selected results for good, be sure to backup your data before messing with any DELETE queries if you're uncertain.
I hope this helps :)
This is the table structure-
Table: test
+------+---------+
| PAGE | CONTENT |
+------+---------+
| 1 | ABC |
+------+---------+
| 2 | DEF |
+------+---------+
| 3 | GHI |
+------+---------+
PAGE is a Primary with datatype INT(11). It does not auto-increment. CONTENT is of the datatype TEXT.
In PHP I do-
$result = mysql_query(SELECT MAX(PAGE) FROM test);
$row = mysql_fetch_array($result);
echo $row["PAGE"];
No output. At all. If I do something like echo "Value : ".$row["PAGE"]; all I see is Value :
The query SELECT * FROM test works just fine though. Am I wrong somewhere using the MAX() syntax?
I want it to return the maximum value of PAGE as of yet.
This should be the code.
$result = mysql_query("SELECT MAX(PAGE) AS max_page FROM test");
$row = mysql_fetch_array($result);
echo $row["max_page"];
Shouldn't you have quotes around that query in mysql_query? I have no idea what PHP will do with such a syntactically inadequate statement, I would have thought it would have given you an error.
In any case, an aggregate function may have a different column name than the column used for it (from memory, DB2 gives it a similar name to the function, like max_page_ or something). You may want to ensure it has the correct column name by forcing the name with something like:
$result = mysql_query("SELECT MAX(PAGE) AS MAXPAGE FROM TEST");
$row = mysql_fetch_array($result);
echo $row["MAXPAGE"];
Try below code
$result = mysqli_query($con,"SELECT max(page2_content_id) AS max_page from page2_content_data");
$row = mysqli_fetch_array($result);
echo $row["max_page"];
Where $con=new mysqli($server,$user,$password,$db_name); and page2_content_data is my table,and page2_content_id is the column name
$connect = mysqli_connect("localhost", "root", "", "carBid") or die("not connected");
//connection to database
$sql2 = "SELECT max(mybid) FROM `bid`";
//simle select statement with max function
$result_set2 = mysqli_query($connect,$sql2);
//query a result fetch
if ($result_set2) {
$rowB = mysqli_fetch_array($result_set2);
//feching a result in array format
echo $rowB['max(mybid)'];
//accessing array by name of column with max() function of mysql
} else {
echo 'No Current Bid';
}
mysqli_close($connect);
I used something like this in my code;
$maxscore_query = mysql_query("SELECT MAX(`score`) FROM `allscores` WHERE`level`='$levelcode'");
echo mysql_result($maxscore_query, 0);
The difference here is the use of WHERE for selecting a group.
And mysql_result($maxscore_query, 0); is easier to manage for me.