Hi I wanted to show port_name instead of port ID ($row['port_name']) so I made this query.
$stmt = $db->prepare("SELECT * FROM reservations
INNER JOIN ports ON reservations.port=ports.id WHERE NOT
((end <= :start) OR (start >= :end))");
$stmt->bindParam(':start', $_POST['start']);
$stmt->bindParam(':end', $_POST['end']);
$stmt->execute();
$result = $stmt->fetchAll();
class Event {}
$events = array();
date_default_timezone_set("UTC");
$now = new DateTime("now");
$today = $now->setTime(0, 0, 0);
foreach($result as $row) {
$e = new Event();
$e->id = $row['id'];
$e->service_id = $row['service_id'].'<br/>';
$e->service_classification = $row['service_classification'].'<br/>';
$e->text = $row['port_name'].'<br/>';
$e->start = $row['start'];
$e->end = $row['end'];
$e->resource = $row['room_id'];
$e->customer = $row['customer'];
$events[] = $e;
}
header('Content-Type: application/json');
echo json_encode($events);
?>
It is working and showing me port names like it should, but when I want to move with event or resize my event (I have calendar of "events") and then I refresh page events stay on previous positions. When I delete JOIN and leave there port_id (reservations.port) everything is working!
resize.php:
class Result {}
$stmt = $db->prepare("UPDATE reservations SET start = :start, end = :end WHERE id = :id");
$stmt->bindParam(':id', $_POST['id']);
$stmt->bindParam(':start', $_POST['newStart']);
$stmt->bindParam(':end', $_POST['newEnd']);
$stmt->execute();
$response = new Result();
$response->result = 'OK';
$response->message = 'Update successful';
header('Content-Type: application/json');
echo json_encode($response);
I don't get it, because I only update new start and end date. Any ideas? Thanks
Related
So I am trying to extract the maximum invoiceNo for current year and this is how I implemented it with PDO:
$sql = 'SELECT MAX(invoiceNo) AS invoiceId FROM invoices WHERE invoiceDate BETWEEN :yearStart AND :yearEnd HAVING invoiceId IS NOT NULL';
if($stmt = $pdo1->prepare($sql)){
$year = date("Y")."-01-01";
$stmt->bindParam(":yearStart", $year);
$year = date("Y")."-12-31";
$stmt->bindParam(":yearEnd", $year);
if($stmt->execute()){
if($stmt->rowCount() == 1){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$invoiceNo = $row['invoiceId'];
$response = date("Y").strval(++$invoiceNo);
}
else{
$response = date("Y")."-0";
}
}
}
However, $response keeps getting assigned to the else clause : .
This is how my DB looks like:
Hence I was expecting the $response to be 2022-2.
I think there is something wrong with my SQL query and I apologize for that, still learning the ropes!
$sql = "SELECT MAX(arbitInvoiceNo) AS invoiceId FROM invoices WHERE invoiceDate BETWEEN :dateStart AND :dateEnd HAVING invoiceId IS NOT NULL";
if($stmt = $pdo1->prepare($sql)){
$dateStart = date("Y")."-01-01";
$stmt->bindParam(":dateStart", $dateStart);
$dateEnd = date("Y")."-12-31";
$stmt->bindParam(":dateEnd", $dateEnd);
if($stmt->execute()){
if($stmt->rowCount() == 1){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$invoiceNo = $row['invoiceId'];
$response = date("Y")."-".strval(++$invoiceNo);
}
else{
$response = date("Y")."-0";
}
}
}
Changed the way I named the variables in PHP and the placeholders in the SQL query. Thank you ADyson for all the help!
in my current project I have to create a JSON array, in which for each day a status with a colour is displayed in a calendar (FullCalendar) and additionally a button with a link is to be displayed for all days where an event is planned.
For this I have two SELECT's which both work on their own. I have already tried some things how to put the results of both SELECT's into one JSON array, but I keep getting the error 'Undefinded Variable'.
How do I have to pack the results of the two SELEC T's put together that all results are displayed correctly?
header('Content-Type: application/json');
include "../../../includes/db.php";
if(isset($_GET['team_id'])) {
$team_id = $_GET['team_id'];
}
$stmt = $connection->prepare("SELECT date FROM date");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$date = $row['date'];
$team_planner_user_status_present = 1;
$team_planner_user_status_absent = 2;
$team_planner_user_status_reservation = 3;
$stmt1 = $connection->prepare("SELECT
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS present,
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS absent,
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS reservation
");
$stmt1->bind_param("sssssssss", $team_id, $date, $team_planner_user_status_present,
$team_id, $date, $team_planner_user_status_absent,
$team_id, $date, $team_planner_user_status_reservation);
$stmt1->execute();
$result1 = $stmt1->get_result();
while($row1 = $result1->fetch_array()) {
$present = $row1['present'];
$absent = $row1['absent'];
$reservation = $row1['reservation'];
if($present >= 5) {
$color = '#a1ff9e';
} else if($present + $reservation >= 5) {
$color = '#fcff9e';
} else {
$color = '#ff9e9e';
}
}
$stmt1->close();
$stmt2 =$connection->prepare("SELECT * FROM game_planned INNER JOIN game_role ON game_planned.match_role_id = game_role.match_role_id WHERE team_id = ? AND game_planned_date = ?");
$stmt2->bind_param("ss", $team_id, $date);
$stmt2->execute();
$result2 = $stmt2->get_result();
while($row2 = $result2->fetch_array()) {
$match_role_name = $row2['match_role_name'];
$game_planned_id = $row2['game_planned_id'];
}
$data[] = array(
'start' => $date,
'display' => 'background',
'color' => $color,
);
if($result->num_rows === 0) {
echo "";
} else {
$data[] = array(
'title' => $match_role_name,
'url' => 'http://localhost/r6team-redesign/team/team.php?team=details-match-plan&match_planned_id='.$game_planned_id,
'start' => $date,
);
}
}
$stmt->close();
echo json_encode($data);
I already create an apps that contain ListView. I uses PHP to connect between android and database. FOr now, I use MySQLi and it works. But when I convert to PDO, the data not displayed. I uses 'Log.d' to trace what the data got. Below is the result:
MySQLi (No error) - {"data":[{"report_id":19,"task_name":"ngantuk","badgeid":"12345","report_date":"04 Dec 2019",.......
PDO (not log show data)
Now, below is current code for MySQLi and PDO
MySQLi
<?php
require_once 'config.php';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = '$badgeid' AND report_status = 'Pending';");
$stmt->execute();
$stmt->bind_result($report_id, $task_name, $badgeid, $report_date, $photo_before, $photo_after, $report_status);
$task = array();
while($stmt->fetch()){
$temp = array();
$temp['report_id'] = $report_id;
$temp['task_name'] = $task_name;
$temp['badgeid'] = $badgeid;
$booked = strtotime($report_date);
$report_date = date("d M Y", $booked);
$temp['report_date'] = $report_date;
$temp['photo_before'] = $photo_before;
$temp['photo_after'] = $photo_after;
$temp['report_status'] = $report_status;
array_push($task, $temp);
}
$response = array();
$response["data"] = $task;
echo json_encode($response);
?>
PDO
require_once 'configPDO.php';
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = :badgeid AND report_status = 'Pending'");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$task = array();
while ($result) {
$temp = array();
$temp["data"] = $task;
array_push($task, $temp);
}
$response = array();
$response["data"] = $result;
echo json_encode($response);
?>
Does anyone know what is problem with my PDO code?
The mysqli code and PDO code are not the same. I copied the code from the mysqli version to the PDO version.
PDOStatement::fetch() gets one row at a time. When you take the results from fetch and put it into the condition of a while loop, you are creating an infinite loop which will eventually run out of memory.
require_once 'configPDO.php';
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = :badgeid AND report_status = 'Pending'");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->execute();
$task = [];
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$temp = [];
$temp['report_id'] = $result['report_id'];
$temp['task_name'] = $result['task_name'];
$temp['badgeid'] = $result['badgeid'];
$booked = strtotime($result['report_date']);
$report_date = date("d M Y", $booked);
$temp['report_date'] = $result['report_date'];
$temp['photo_before'] = $result['photo_before'];
$temp['photo_after'] = $result['photo_after'];
$temp['report_status'] = $result['report_status'];
$task[] = $temp;
}
$response = [];
$response["data"] = $task;
echo json_encode($response);
My code working fine , but i got this error :
SQLSTATE[HY000]: General error
I searching on google and someone say that it's may SQLi
What is this ? And how can i fix that ?
thanks and sorry for my poor english
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Anti Brute Forced
$stmt = $db_con->prepare("
SELECT * FROM users
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$users_username = $row["users_username"];
$users_password = $row["users_password"];
$users_wrong_password = $row["users_wrong_password"];
if ($users_wrong_password <= 3 && isset($_GET["username"],$_GET["password"]) && $_GET["username"] == $users_username && $_GET["password"] != $users_password){
$u = $users_wrong_password + 1;
$g = 0;
$g = $_GET['username'];
$stmt = $db_con->prepare("
UPDATE users
SET users_wrong_password = $u
WHERE users.users_username = '$g'
");
$stmt->execute();
}
if ($_GET["username"] == $users_username && $users_wrong_password >= 4){
echo "Your Account Was Banned For 1 Hours";
die;
}
}
$g = $_GET['username'];
$stmt = $db_con->prepare("SELECT * FROM users where users_username = '$g'");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$ss = $row["users_wrong_password"];
}
if($ss <= 3){
$g = 0;
$g = $_GET['username'];
$stmt = $db_con->prepare("
UPDATE users
SET users_wrong_password = 0
WHERE users_username = '{$_GET['username']}'
");
$stmt->execute();
}
// Anti Brute Forced
[Solved]
Edit:
$g = $_GET['username'];
$p = $_GET['password'];
$stmt = $db_con->prepare("
SELECT * FROM users where users_username = '$g' and users_password = '$p'
");
I found this problem in a similar another way
"errorInfo":["HY000"]
How does "HY000" error happen?
It happens when you are updating, deleting or inserting data with PDO, and you try to fetch it's result.
The solution, just do not use fetch or fetchAll methods after executing an updating, deleting or inserting. Surely, it does not make sense to fetch it's result!
Example:
$stmt = $db_con->prepare("
UPDATE users SET name = 'Renato' WHERE ID = 0
");
$stmt->execute();
$stmt->fetch(PDO::FETCH_ASSOC); // The mistake is here, just remove this line
$stmt->fetchAll(PDO::FETCH_ASSOC); // It will cause troubles too, remove it
Solving the problem in a loop
The solution is changing the statement variable name inside loop, or fetch all before starting loop:
Solution: Changing variable name
$stmt = $db_con->prepare("
SELECT * FROM users
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// ...
// This is another statment
$another_stmt = $db_con->prepare("
UPDATE users
SET users_wrong_password = $u
WHERE users.users_username = '$g'
");
$another_stmt->execute();
}
Solution: Fetch all data from query before loop
$stmt = $db_con->prepare("
SELECT * FROM users
");
$stmt->execute();
// Everything is fetched here
$results = $stmt->fetchAll(PDO::FETCH_ASSOC)
foreach($results as $row){ // Another way to loop through results
$stmt = $db_con->prepare("
UPDATE users
SET users_wrong_password = $u
WHERE users.users_username = '$g'
");
$stmt->execute(); // Be happy with no troubles
}
I think there are multiple preparations of the same query.
Solution Get the query preparation out of the while.
code:
//... your code
$stmt1 = $db_con->prepare("
UPDATE users
SET users_wrong_password = $u
WHERE users.users_username = '$g'
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$users_username = $row["users_username"];
$users_password = $row["users_password"];
$users_wrong_password = $row["users_wrong_password"];
if ($users_wrong_password <= 3 && isset($_GET["username"],$_GET["password"]) && $_GET["username"] == $users_username && $_GET["password"] != $users_password){
$u = $users_wrong_password + 1;
$g = 0;
$g = $_GET['username'];
$stmt1->execute();
//...
}
I have this function that loads an array from a table called 'customer' it works fine, but I also want it to check if the customer has expired and if so display an error
So I have code below that to check if the id_expiry_date is over, but I'm having difficulty working out where to put it in the function. Tried a few things, but just seems to break. Please assist.
function customer_load_by_id($id)
{
$dbh = dbh_get();
$id = array();
$sql = 'select c.* ' .
'from customer c ' .
'where c.cust_id = (select max(cust_id) from customer where id = ?)';
$stmt = $dbh->prepare($sql);
$stmt->execute(array($id));
$r = $stmt->fetch();
if (!is_bool($r)) {
$fields = id_get_fields();
foreach ($fields as $field) {
$n = $field['name'];
$id[$n] = $r[$n];
}
}
dbh_free($dbh);
$exp_date = "$id_expiry_date";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) {
//continue happily
} else
{
//don't continue
}
return $id;
}
// One of the fields in the array above is id_expiry_date
I do not really get how you SQL schema is but, using Pomm, I would write the following code:
<?php
use PommProject\Foundation\Pomm;
$loader = require __DIR__ . '/vendor/autoload.php'; //<- setup autoloading
$pomm = new Pomm(…); // <- connection params go there
$sql = <<<"SQL"
select
c.*,
c.expiry_date < now() as is_expired
from customer c
where c.cust_id = (select max(cust_id) from customer where id = $*)
SQL;
$result = $pomm
->getDefaultSession()
->getQueryManager()
->query($sql, [$id])
->current() // <- Take the first row if exist
;
if ($result) {
if ($result['is_expired']) { //<- 'is_expired' is converted as boolean
echo "expired";
} else {
echo "not expired";
}
} else {
echo "no result";
}