I have a small database with products and prices. I want to calculate the sum of the column "orderpris", in my table called orders. And print this to the screen. Not sure if I'm anywhere near the solution but I thought this would work but it dont. What have I done wrong?
<?php
function sum() {
/* Connect to database */
$db = new mysqli('localhost', 'admin2', 'password', 'myshop');
if($db->connect_errno > 0){
die('Fel vid anslutning [' . $db->connect_error . ']');
}
$results = mysqli_query("SELECT sum(orderpris) FROM orders") or die(mysqli_error());
while ($rows = mysqli_fetch_array($results)) {
}
?>
<div>
Total: <?php echo $rows['sum(orderpris)']; ?>
</div>
<?php }
?>
<?php
sum();
?>
Try this:
<?php
function sum() {
/* Connect to database */
$db = new mysqli('localhost', 'admin2', 'password', 'myshop');
if ($db->connect_errno > 0) {
die('Fel vid anslutning [' . $db->connect_error . ']');
}
$results = mysqli_query($db, "SELECT sum(orderpris) as total FROM orders") or die(mysqli_error());
while ($rows = mysqli_fetch_array($results)) {
$iResult = 'Total:'.$rows['total'];
}
return $iResult;
}
echo sum();
1- I have changed:
$results = mysqli_query($db, "SELECT sum(orderpris) as total FROM orders") or die(mysqli_error());
Instead:
$results = mysqli_query("SELECT sum(orderpris) FROM orders") or die(mysqli_error());
As you can see, mysqli_query function needs at least two parameters:
-A link identifier, in your case it is $db
-The query string.
2- I have added an alias 'total' to the query
-It works, but try to don't use database connection into your function, suppose that you have several functions and you need to connect to database , you will be repeating the same action every time.
-Try to move sum() function to a class
-Try to create a unique way to database connection and not several connections for each function.
Related
I need help with some code. I want to select data from mySQL to a graph on my web page.
The data must be from the current logged in user, and when I select data to a card it works fine, but when I select it to a graph the graph disappears.
I'm using this code for the cards, and it works fine:
$sql = "SELECT energyexpenditure FROM energy4project WHERE user_id = '{$_SESSION["user_id"]}' ORDER BY time_stamp DESC LIMIT 1;";
This is the code for my current graph that don't show data based on logged in user:
<?php
header('Content-Type: application/json');
$host = "localhost";
$user = "`blabla";
$pwd = "blabla";
$db = "blabla";
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT energyexpenditure, time_stamp FROM energy4project ORDER BY time_stamp DESC LIMIT 7;";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
When I implement the code from the cards in the graph code it doesn't work.
Why does the SELECT WHERE user = '{$_SESSION["user_id"]} not work in the graphs?
If I understood good your Mysql query return an empty result. Try to modify your code as follows:
if(!$result = $conn->query($sql)) {
echo "query error.";
die();
}
$data = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
/* free result set */
$result->free();
/* close connection */
$conn->close();
//uncomment the below line if you want to check de result of your mysql query because it seems be good.
//var_dump($data); die(); echo "<pre>";
echo json_encode($data);
So if you don't have any mysql error, verify your database name, table name are correctly and if it has data in your table.
Reference: https://www.php.net/manual/en/mysqli-result.fetch-array.php
Regards
Here is the webpage in question
http://liamure.xyz/rsk/getdata.php
Here is the database
Database
And here is the SQL code
<?php
$con=mysqli_connect('host', 'user', 'Password', 'database');
if(mysqli_connect_errno())
{
echo "Failed Connection" . mysqli_connect_errno();
}
else
{
$sth = mysqli_query("SELECT * FROM quotes");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
echo"1";
$rows[] = $r;
}
print json_encode($rows);
}
?>
When the webpage is run all that gets returned is "[]" (You can see this by clicking the URL above)
The first argument of mysqli_query function is the connection link object:
$sth = mysqli_query($con, "SELECT * FROM quotes");
I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}
I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];
I have a db, am trying to extract values into a list
Here is the code I am trying to run (I had to adapt it from elsewhere), which should return an array, from which I want to select the AllianceName attribute
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($dbname, $con);
$options = array();
$options[] = "<option value=''>--?--</option>";
$query = "
SELECT *
FROM `City`
GROUP BY `AllianceName`
";
$db = mysqli_query($query);
foreach ( $db as $d ) {
$options[] = "<option value='{".$d['AllianceName']."}'></option>";
}
?>
<select class="" id="articles" size="1" name="articles">
<?php echo implode("\n", $options); ?>
</select>*/
Right now this only returns the --?-- that I have defined in the options array. It does not parse any of the values from the query. I know the query by itself is correct since I have run it exactly in this syntax in the SQL server and it works.
I am pretty sure that this is a syntax error ... var_dump($db) gives me a bool(false) output.
Here's the latest code I am using:
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
?>
<select class="Select" id="articles" size="1" name="articles">
<?php
$sql = <<<SQL
SELECT DISTINCT `AllianceName`
FROM `City`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo "<option value="'.{$row['AllianceName']}.'"></option>";
}
?>
</select>
The query by itself runs fine when I just echo the results. Trying to put it into a dropdown fails every time. No values get populated.
There are a couple problems here.
First you don't need the GROUP BY 'AllianceName' in your query, you are not performing any functions on your data, that might have been causing you to not return any results.
Secondly, normally you loop through query results with a while loop. You don't have to, but its common practice, so your code should look like this..
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//there is no need to make an array first, just have it spit out the options if you aren't making a class or function
?>
<select class="" id="articles" size="1" name="articles">
<?php
$query = "SELECT * FROM `City` ";
$db = mysqli_query($query);
while ( $d=mysqli_fetch_assoc($db)) {
echo "<option value='{".$d['AllianceName']."}'></option>";
}
?>
</select>
Try that out and see if it works for you.
From the mysqli_query() docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
So what you have after the query succeeded is a mysqli_result object. Now you have to fetch the result into an (associative) array or object, row by row.
if($query === false) die('Query failed to execute');
while($row = $result->fetch_assoc()) {
echo $row['AllianceName'] . PHP_EOL;
}
All this is described in hundreds of tutorials in the web, so please read one of these. I recommend these written in the current decade, e.g. http://codular.com/php-mysqli
Here is the code that finally worked. Both #Syndrose and #Zombiehunter provided clues to this.
#Syndrose - you might want to take into account the syntax used here as this is what was failing from your codebase...especially the syntax for the echo tag line.
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = <<<SQL
SELECT DISTINCT `AllianceName`
FROM `City`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
?>
<select style="width:300px" class="" id="AllianceName" size="1" name="Alliance Name">
<?php
while($row = $result->fetch_assoc()){
echo '<option value='.$row['AllianceName'].'>'.$row['AllianceName'].'</option>';
}
?>
</select>