Fatal error: Call to undefined method mysqli_result::format() - php

I know that the error says that format isn't a valid code, but I used it before and it worked fine. So I hope someone knows a code to replace it with or now how to fix it.
require_once 'config.php';
$checker = "SELECT StartTime FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$checker2 = "SELECT EndTime FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$checker3 = "SELECT Minutes FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$result1 = mysqli_query($mysqli, $checker);
$result2 = mysqli_query($mysqli, $checker2);
$minutes = mysqli_query($mysqli, $checker3);
$starttime = new DateTime($result1);
$endtime = new DateTime($result2);
while($starttime <= $endtime)
{
echo "<option value='".$starttime->format('H:i:s')."'>".$starttime->format('H:i:s')."</option>";
$starttime = date_add($starttime, date_interval_create_from_date_string($minutes, ' min'));
}
echo " </select>";
and above I grab the vars out of the database

The problem is mysqli_query returns a mysqli_result which you need to read before using:
require_once 'config.php';
$checker = "SELECT StartTime, EndTime, Minutes FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$result = mysqli_query($mysqli, $checker); //Execute query
if (!$result) { //Result may be false if there's an error
echo "Error getting result";
}
$row = mysqli_fetch_assoc($result); //Put first result in an array
if (!$row) { // $row will be false if there's no result
echo "No data found";
}
//Notice how the array entry keys match the columns in the query.
$starttime = new DateTime($row["StartTime"]);
$endtime = new DateTime($row["EndTime"]);
$minutes = $row["Minutes"];
while($starttime <= $endtime)
{
echo "<option value='".$starttime->format('H:i:s')."'>".$starttime->format('H:i:s')."</option>";
$starttime = date_add($starttime, date_interval_create_from_date_string($minutes, ' min'));
}
echo " </select>";

Related

subtract two different sum of column from two different table in select query

I have two tables with the name of add_sell and add_expense.
I have inserted some of value into the tables. I wanted to get the total profit result. I did it myself but the result is showing 0 . Now how can I do that. I also give the total profit formula. Is anyone here to help me? Here is the code given below
function totalSell(){
global $conn;
$sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
$result = $conn->query($sql);
$getDate = date('d/m/Y');
if(mysqli_num_rows($result) > 0){
while($fetch = mysqli_fetch_array($result)){
echo "SR ".$fetch['Sumearning'];
}
}
}
function totalExpense(){
global $conn;
$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
$run_ex = $conn->query($ex);
if (mysqli_num_rows($run_ex) > 0) {
while ($tex = mysqli_fetch_array($run_ex)) {
echo "SR ".$tex['Sumexpense'];
}
}
}
function totalProfit(){
global $conn;
$sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
$result = $conn->query($sql);
$getDate = date('d/m/Y');
while($fetch = mysqli_fetch_array($result)){
$fetch['Sumearning'];
echo "Total Earning : ".$totalEarning = "SR ".$fetch['Sumearning'];
}
$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
$run_ex = $conn->query($ex);
while ($tex = mysqli_fetch_array($run_ex)) {
$tex['Sumexpense'];
echo "Total Expense : ".$totlaExpenss = "SR ".$tex['Sumexpense'];
}
echo "Your totla Profit is : ".$totalprofit = $totalEarning - $totlaExpenss;
}
Total profit result you can get from query itself.
$sql = "SELECT SUM(`sell_amount`)-(SELECT SUM(`expense_amount`) FROM `add_expense` WHERE expense_amount = `expense_amount`) AS `PROFITLOSS` FROM `add_sell` WHERE sell_amount = `sell_amount`";
Note: as Sumearning and as Sumexpense Removed instead you will get as PROFITLOSS
Do you mean getting the difference between the Sum earnings and the Sum expenses?
Because you can do it like this?
$Total = $tex['Sumexpense'] - $fetch['Sumearning'];
Echo $total;

Getting multiple data from database (or so)

I'm trying to get multiple bookings from my database for a hotel project
when i tried to get the bookings from my database i only recieved one booking it should display/select multiple bookings.
This is my php code:
(formulier.php)
<?php
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) { include_once 'source.php';
}
echo "<br>formulier.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}
?>
And this is my other php code: (source.php)
<?php
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
}
echo "source.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}
?>
this is my database: (dt_tb)
https://gyazo.com/966efdf144a8cd1a74fa04a8127cd8f4
This is what i receive: (Website)
https://gyazo.com/1384bdafb5055f5777a40e88baccdbdd
I know my code is messed up badly and tried to solve it for quite some time.
I don't know why you need two files. You can join them to single loop.
<?php
$dt1 = !empty($_POST['date1']) ? $_POST['date1'] : null;
$dt2 = !empty($_POST['date2']) ? $_POST['date2'] : null;
if (!$dt1 || !$dt2) {
throw new Exception("No dates passed!");
}
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
echo "check-in: {$row['dt']}<br/>";
echo "check-out: {$row['dt2']}<br/>";
echo "<br/>";
}
} else {
echo "No bookings found between {$dt1} and {$dt2}";
die();
}
?>
What was wrong:
require_once is called only for first iteration, no further calls was made. It's used mostly when including classes or some configs, that must be included only once in whole logic.
You try to echo your data outside loop inside source.php
You echo passed parameters to server, but not actual database record entries. Changed $dt1 to $row['dt'] and $dt2 to $row['dt2']
You repeated the query in both files! Why?
As you typed, you don't need to include 2 lines! , you can add them directly:
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
echo "source.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
echo "<br>formulier.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}

fetchArray() not working in SQLite

I'm working with SQLite on my webserver and have had no problems until now.
$sql = "SELECT * from TeammateCurrent;";
$ret = $db->query($sql);
if($ret != false) {
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$uniqueid = $row['uniqueID'];
$name = $row['Name'];
$lineID = $row['LineID'];
$job = $row['Job'];
$sunday = $row['Sunday'];
$monday = $row['Monday'];
$tuesday = $row['Tuesday'];
$wednesday = $row['Wednesday'];
$thursday = $row['Thursday'];
$friday = $row['Friday'];
$saturday = $row['Saturday'];
//echo $name."<br>".$lineID."<br>".$job."<br>".$sunday."<br>".$monday."<br>".$tuesday."<br>".$wednesday."<br>".$thursday."<br>".$friday."<br>".$saturday."<br><br>";
$sql = "INSERT INTO TeammateHistory (uniqueID, Name,LineID,Job,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday)
VALUES (NULL, '$name','$lineID','$job','$sunday','$monday','$tuesday','$wednesday','$thursday','$friday','$saturday');";
$ret = $db->exec($sql);
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
$sql2 = "UPDATE TeammateCurrent set Sunday='$day0', Monday='$day1', Tuesday='$day2', Wednesday='$day3', Thursday='$day4', Friday='$day5', Saturday='$day6' where uniqueID='$uniqueid';";
$ret = $db->exec($sql2);
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
}
} else {
echo "Query not successful";
}
When the code above executes, I get the error Fatal error: Call to a member function fetchArray() on a non-object in /home/xxxx/public_html/xxxx.com/trg/rc2/db/startNewWeek.php on line 39
I've ran code just like this on other pages and they work fine, I'm at a total loss here.
My tables:
you're reusing the variable $ret. You should have a different return variable for the SELECT statment and UPDATEs. In the second loop you're trying to do a fetchArray() of the return of an UPDATE statement.

PHP SQL loop outputs as 0 rows

I am trying to create a PHP loop to show the players the tournaments they are partaking in. I tried the function on phpMyAdmin, and I got the result that I wanted. But when I try to run this simple script on PHP, it outputs as 0 rows.
index.php
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
if($mybb->user['uid']) {
$sql = "SELECT * FROM players, tourneys WHERE players.forumname = 1 AND players.tid = tourneys.id";
$result = mysqli_query($conn, $sql);
// output data of each row
if (mysqli_num_rows($result) > 0) {
// output data of each ro
while($row = mysqli_fetch_assoc($result)) {
$name = $row['name'];
$date = $row['date'];
$time = $row['time'];
echo $name;
echo $date;
echo $time;
}
} else {
echo "0 rows";
}
}
The problem is not in "if ($mybb->user['uid']) {" as suggested by #Dagon. Try to leave the well indented code to avoid this kind of confusion. Run the code below and post the the DB error output.
Try this:
<?php
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
if ($mybb->user['uid']) {
$player_forumname = '1';
// Return only the necessary fields
$sql = "SELECT tourneys.name, tourneys.date, tourneys.time
FROM tourneys
INNER JOIN players ON players.tid = tourneys.id
WHERE players.forumname = {$player_forumname}";
$result = mysqli_query($conn, $sql);
// If the query fails display the error
if ($result === FALSE) {
die('MySQLi Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) == 0) {
die('0 rows');
}
// Returns only the associative array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$date = $row['date'];
$time = $row['time'];
echo 'Name:',$row['name'],'Date:',$row['date'],'Time:',$row['time'];
}
}

PHP not transferring to mysql database

Okay so I am new to PHP and attempting to make a script that takes all of the data from a mysql database I have of stock prices and then looks to see if there was an increase in the stock price during after hours trading (by comparing one day's close price with the next day's open price). I have set up a few scripts like this that work, but for some reason this script isn't copying the data into my sql database and I am completely stumped as to why it won't.When I set up echo statements throughout I discovered that my code is seemingly being executed everywhere but the data isn't transferring. Any help is greatly appreciated.
<?php
include("../includes/connect.php");
function masterLoop(){
$mainTickerFile = fopen("../tickerMaster.txt","r");
while (!feof($mainTickerFile)){
$companyTicker = fgets($mainTickerFile);
$companyTicker = trim($companyTicker);
$nextDayIncrease = 0;
$nextDayDecrease = 0;
$nextDayNoChange = 0;
$total = 0;
$overnight_change = 0;
$overnight_change_pct = 0;
$sumOfIncreases = 0;
$sumOfDecreases = 0;
$sql = "SELECT date, open, close, percent_change FROM $companyTicker";
$result = mysql_query($sql);
if($result){
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$percent_change = $row['percent_change'];
$open = $row['open'];
$close = $row['close'];
$sql2 = "SELECT date, open, close, percent_change FROM $companyTicker WHERE date > '$date' ORDER BY date ASC LIMIT 1";
$result2 = mysql_query($sql2);
$numberOfRows = mysql_num_rows($result2);
if($numberOfRows==1){
$row2 = mysql_fetch_row($result2);
$tom_date= $row2[0];
$tom_open= $row2[1];
$tom_close= $row2[2];
$tom_percent_change= $row2[3];
if ($close == 0){
$close = $tom_open;
}
$overnight_change = $tom_open - $close;
$overnight_change_pct = ($overnight_change/$close)*100;
if($overnight_change_pct > 0){
$nextDayIncrease++;
$sumOfIncreases += $tom_percent_change;
$total++;
}else if($overnight_change_pct < 0){
$nextDayDecrease++;
$sumOfDecreases += $tom_percent_change;
$total++;
}else{
$nextDayNoChange++;
$total++;
}
}else if ($numberOfRows==0){
$total = 1;
$nextDayIncrease = 1;
$nextDayDecrease = 1;
}else{
echo "You have an error in analysis_c3";
}
}
}else{
echo "unable to select $companyTicker <br />";
}
$nextDayIncreasePercent = ($nextDayIncrease/$total) * 100;
$nextDayDecreasePercent = ($nextDayDecrease/$total) * 100;
$averageIncreasePercentage = $sumOfIncreases/$nextDayIncrease;
$averageDecreasePercentage = $sumOfDecreases/$nextDayDecrease;
insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage);
}
}
function insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage){
$buyValue = $nextDayIncreasePercent * $averageIncreasePercentage;
$sellValue = $nextDayDecreasePercent * $averageDecreasePercentage;
$trueValue = $buyValue + $sellValue;
$query="SELECT * FROM analysisOvernightGain5 WHERE ticker='$companyTicker' ";
$result=mysql_query($query);
$numberOfRows = mysql_num_rows($result);
if($numberOfRows==1){
$sql = "UPDATE analysisOvernightGain5 SET ticker='$companyTicker',daysInc='$nextDayIncrease',pctOfDaysInc='$nextDayIncreasePercent',avgIncPct='$averageIncreasePercentage',daysDec='$nextDayDecrease',pctOfDaysDec='$nextDayDecreasePercent',avgDecPct='$averageDecreasePercentage',buyValue='$buyValue',sellValue='$sellValue'trueValue='$trueValue' WHERE ticker='$companyTicker' ";
mysql_query($sql);
}else{
$sql="INSERT INTO analysisOvernightGain5 (ticker,daysInc,pctOfDaysInc,avgIncPct,daysDec,pctOfDaysDec,avgDecPct,buyValue,sellValue,trueValue) VALUES ('$companyTicker', '$nextDayIncrease', '$nextDayIncreasePercent', '$averageIncreasePercentage', '$nextDayDecrease', '$nextDayDecreasePercent', '$averageDecreasePercentage', '$buyValue', '$sellValue','$trueValue')";
mysql_query($sql);
}
}
masterLoop();
?>
you have missed , at ,sellValue='$sellValue'trueValue='$trueValue'
it should be ,sellValue='$sellValue',trueValue='$trueValue'

Categories