ORDER BY is not working for mysql table [closed] - mysql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a dummy database saved in phpmyadmin.I am trying to sort the data on the basis of column user_uid.
Here is some of my database
The php code that i am using to sort the table is
<?php
include_once 'dbh.inc.php';//file contains the variables req to connect to database
$sql = "SELECT * FROM client
ORDER BY user_uid;";
$result = mysqli_query($conn,$sql);
if(($result))
{
$row = array();
($row = mysqli_fetch_array($result));
echo($row['client_name']);
}
However this doesn't seem to work.What am I doing wrong with the code?
Additional info: user_uid is a foreign key and the reference to the user_uid is from another table named users

Well in your code you have written
ORDER BY cost_per_session
Just change it to
ORDER BY user_id
you can use ASC or DESC for ascending or descending order.

Your code shows only one record. Here is a working example making use of the needed while loop to display the client_name of each fetched record:
include_once 'dbh.inc.php';
$sql = 'SELECT * FROM client
ORDER BY user_uid';
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['client_name'] . '<br>';
}
}
I removed all the unneeded parenthesis around the vars and the semicolon at the end of the sql statement.
Good luck.
Edit 1: I corrected $connection to $conn.
Edit 2: I implemented the check on the number of rows ($result->num_rows > 0) instead of on the $result itself (which is always an object of type mysqli_result and whos check therefore always returns true - even when no records are found).

Related

Create variable from MySQL datatable that can be used in HTML code

So I have a MySQL database and would like to create variables from that database that I can use in HTML code.
For example if I use <video blablabla some stuff src="phpVariable" /video>
I don't want to have a static URL in the HTML code. It should be assigned to a variable based on an SQL query. What is the best way to do this?
First, you need to retrieve the data from the database that you wish to use, using a database query. From there, you can loop through all the results and output them.
Replace 'tablename' with the name of the database table and 'columnName' with the column name.
$con should be used to connect to your database. See https://www.php.net/manual/en/pdo.connections.php
$stmt = $con->prepare("SELECT * FROM tablename");
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['columnName'];
}
If you only needed to retrieve one record, change the code to:
$stmt = $con->prepare("SELECT * FROM tablename");
$stmt->execute();
$row = $stmt->fetch();
echo $row['columnName'];
You can also store the retrieved data as a variable, like this:
$variableName = $row['columnName'];
// Then to use the variable in your code:
echo'<video src='.$variableName.'</video>';
This is very basic PHP though. Have you looked at some online guides?

Nesting a second query inside a list of unique column values [duplicate]

This question already has answers here:
PHP PDO group query results by column name
(2 answers)
Closed 3 years ago.
Beginner here, be gentle please. I have a table in which one column is book titles and another is their corresponding authors. I'm using PDO to connect to the database and display the results of a query on a webpage. Basically I want each UNIQUE author displayed once, and then a list of each book title that author wrote beneath, like so:
Author 1
title1
title2
Author 2
title3
title4
Query to get a list of distinct authors:
<?php try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT DISTINCT author FROM booktable;"
$statement = $connection->prepare($sql);
$result = $statement->fetchAll();
} ?>
Foreach loop to display each author:
<?php foreach ($result as $row) { ?>
<p><?php echo ($row["author"]); ?></p>
<?php } ?>
So far so good, this gives me a list of unique authors. For the titles, I was trying to do another foreach loop nested inside the first to display a second query, but I can't figure out how to get only the author the loop is currently on. I tried setting a variable inside the loop like so:
<?php foreach ($result as $row) { ?>
<p><?php echo ($row["author"]); ?></p>
<?php $currentauthor = ($row["author"]); ?>
<?php foreach ($result2 as $row2) { ?>
<p><?php echo ($row2["title"]); ?></p>
<?php } ?>
<?php } ?>
And then adding another query in my original TRY (along with a corresponding new connection and fetch statement):
$sql2 = "SELECT * FROM booktable WHERE author = '$currentauthor'";)
But that returns nothing because the $currentauthor variable doesn't exist outside the foreach loop. So there's my issue. Am I going about this the wrong way?
It looks like you should be able to do what you are attempting with a single, non-joining query. You can use SELECT * FROM booktable ORDER BY author, and loop through it's results, only outputting author data when you detect the current record has a different author than the previous one (and for the first record obviously).
A note since you're new: the * in SELECT * is generally considered bad form for final, deployed queries; I merely used it here as a placeholder since I do not know all the fields you want data from. It is best to specify all the fields you will be using, as it: (1) documents the data used without having to inspect all code that works with the data, (2) makes the query less fragile by not depending on the table definition for column order, (3) makes the query break if a used field is removed from the table, rather than later code that assumes the value will be there (which then has to be tracked back to the query), (4) keeps the amount of data that needs to be collected together and transferred to only what is needed, and (5) more...

database normalization do I need it [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've read a lot about normalization and I still can't fully understand it/I'm not sure how to normalize this. This is how my database currently looks, does it even need to be normalized? If so, where do I even start?
http://i.imgur.com/L43fHS6.png this is what it currently looks like
You will want to have 1 row per user_ID so you can easily access all the data.
e.g. for your gameID 5002947 (row11) this needs to be split into the following:
id setup_id user_ID
5002947 997 563749
5002947 997 500243
5002947 997 536271
...
You have two options. Create a complex SQL query that will handle this (I can't supply this unfortunately but I'm sure others could) or use php.
PHP method
Select all rows and explode the userID into an array.
loop through this array and insert back into the database.
Depending on the number of rows and userIDs you have this may take a while to execute.
e.g.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$query = 'SELECT * FROM table';
$data = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_array($data))
{
$data[] = array("gameid"=>$row['game_ID'], "setupid"=>$row['setup_ID'],"userid"=>str_getcsv($row['user_ID'])); /*And all your other information*/
}
for($i=0; $i<count($data); $i++) {
$gameid = $data[$i]['gameid'];
$setupid = $data[$i]['setupid'];
/*Other info you need*/
for ($x=0; $x<count($data[$i]['userid']);$x++) {
$userid = $data[$i]['userid'][$x];
if ($stmt = $mysqli->prepare("INSERT INTO newtable (game_ID, setup_ID, user_ID) VALUES (?, ?, ?)")) {
$stmt->bind_param('iii', $gameid ,$setupid ,$userid);
if (!$stmt->execute()) {
$stmt->close();
}
}
}
}

MYSQL Prepared Statements Select Row_Count

I have a simple SQL Query:
$stmt = $db_main->prepare("SELECT id FROM user WHERE username=? AND mail=? LIMIT 1");
$stmt->bind_param('ss', $username, $mail);
$stmt->execute();
And I want to know, if it found an user. So I want to count the rows found.
I already tried to use rowCount (Not safe for SELECT) or num_rows or just looking if the result id is numeric (Which '' would not be, I hoped...)
There has to be an easy way to count the selected row, hasn't be?
Check number of rows returned with:
$stmt->num_rows;
Check for instance this site.
p.s.: added as per question in comment: use fetch() in order to get the next record.
...
$stmt->execute();
$stmt->bind_result($user_id); // access id
$stmt->store_result(); // optional: buffering (see below)
if ($data = $stmt->fetch()) {
do {
print("Id: " . $user_id);
} while ($data = $stmt->fetch());
} else {
echo 'No records found.';
}
Regarding store_result() from the documentation:
"You must call mysqli_stmt_store_result() for every query ..., if and only if you want to buffer the complete result set by the client ..."

How to display the values returned by count in SQL

i keep having this error "mysql_fetch_array() expects parameter 1 to be resource, null given in" when i try to display the returned value of count in sql. heres my code.
$query="SELECT med_rec_ID, COUNT(med_rec_ID)
FROM med_issue
WHERE MONTH(issue_date) = MONTH('2013-02-05')
GROUP BY med_rec_ID";
$result= mysql_query($query);
while($count = mysql_fetch_array($display3)){
echo $count[0];
}
i have tried to run the query in sql alone it displays 2 columns (the med_rec_ID, and the COUNT). guys how do i display the count and fix the error too?
First of all, don't use mysql_* functions since they're deprecated. Use mysqli or PDO.
Secondly, look at what you're passing into the fetch_array function.
You probably want to do something like:
$link = mysqli_connect("localhost", "admin", "pass", "db_name");
$result = mysqli_query($link, $sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$medIds[] = $row['med_rec_ID'];
...
}
Then fix the count by giving it an alias.
Please note that you should actually store how you access the DB in a more secure manner, but I use this only to illustrate the example. Here's a pretty good post: How to create global configuration file?
Is your query even executing? that error will happen if mysql_query doesnt return the resource, in case query fails
$query="SELECT med_rec_ID, COUNT(med_rec_ID) as C FROM med_issue where MONTH(issue_date) = MONTH('2013-02-05') GROUP BY med_rec_ID";
$result= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row["C"];
}
Note: Please do not use mysql_* functions anymore
Give it an alias:
SELECT
med_rec_ID,
COUNT(med_rec_ID) TheCount
FROM med_issue
where MONTH(issue_date) = MONTH('2013-02-05') GROUP BY med_rec_ID
then you can select that column TheCount inside the while loop with $row['TheCount'], also use lope through the $result:
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo $row['TheCount'];
}