how to sum table1 and table2 (simple sum) - php

How I can sum Table1 and Table2
If table1 have more than one entry status "0" and table2 also more than one entry status "0" then sum Table1 + Table2.
Example
Table1 have 3 entrys with status "0" and table2 have 2 entrys with status "0" then sum is 2
Like first table = 1 and second table = 1
And if table1 have entries and table2 doesnt have entries then sum is 1
and if Both doesnt have entries then sum is 0
I tryed this if statements:
require_once('../../function.php');
try{
$database = new Connection();
$db = $database->openConnection();
$status = 0;
$sql = "SELECT ( SELECT COUNT(*) FROM contact WHERE status = 0 ) AS contact, COUNT(*) AS ordr FROM orrdr WHERE status = :status";
$qry = $db->prepare($sql);
$qry -> bindParam(':status', $status, PDO::PARAM_INT);
$qry -> execute();
$count = $qry->fetchColumn();
} catch (PDOException $e) {
echo "There is some problem in connection: " . $e->getMessage();
}
if ($count['contact'] => 1 && $count['ordr'] => 1) {
echo "2";
} elseif (empty($count['contact']) && empty($count['ordr']) {
echo "0";
} elseif () {
# code...
}
This is counting for notifications.
Status 1 is readed notification and status 0 is not readed notification.
I didnt finish my statements because I know this is wrong way to do it.

You can use the following SQL:
SELECT SUM(x.cnt)
FROM (
SELECT IF(COUNT(*) > 0, 1, 0) AS cnt FROM contact WHERE status = 0
UNION ALL
SELECT IF(COUNT(*) > 0, 1, 0) FROM orrdr WHERE status = 0
)x
So you can use the following PHP code:
require_once('../../function.php');
try {
$database = new Connection();
$db = $database->openConnection();
$status = 0;
$sql = "SELECT SUM(x.cnt) FROM (SELECT IF(COUNT(*) > 0, 1, 0) AS cnt FROM contact WHERE status = :status UNION ALL SELECT IF(COUNT(*) > 0, 1, 0) FROM orrdr WHERE status = :status)x";
$qry = $db->prepare($sql);
$qry -> bindParam(':status', $status, PDO::PARAM_INT);
$qry -> execute();
$count = $qry->fetchColumn();
} catch (PDOException $e) {
echo "There is some problem in connection: " . $e->getMessage();
}
echo $count;
If you need to know the sums of both queries you can use the following:
require_once('../../function.php');
try {
$database = new Connection();
$db = $database->openConnection();
$status = 0;
$sql = "SELECT (SELECT COUNT(*) FROM contact WHERE status = :status) AS cnt_contact, (SELECT COUNT(*) FROM orrdr WHERE status = :status) AS cnt_orrdr";
$qry = $db->prepare($sql);
$qry -> bindParam(':status', $status, PDO::PARAM_INT);
$qry -> execute();
$count_contact = $qry->fetchColumn(0);
$count_orrdr = $qry->fetchColumn(1);
} catch (PDOException $e) {
echo "There is some problem in connection: " . $e->getMessage();
}
if ($cnt_contact >= 1 && $cnt_orrdr >= 1) {
echo "2"; //both available.
} elseif($cnt_contact >= 1 && $cnt_orrdr == 0) {
echo "1"; //only contact available.
} elseif ($cnt_orrdr >= 1 && $cnt_contact == 0) {
echo "1"; //only orrdr available.
} elseif ($cnt_orrdr == 0 && $cnt_contact == 0) (
echo "0"; //nothing available.
}
//simpler solution instead of "if" above:
//echo (($cnt_contact > 0 ? 1 : 0) + ($cnt_orrdr > 0 ? 1 : 0));

Related

how can foreach mysql result?

I have 2 Columns in mysql. valami2 and playerID in table players_extra.
I will the following:
give 3000 coppers for the first row in valami2, then 2500 coppers for the second(then each row -500 coppers until the 5th place)....after the 5th place give 500 until the 10th place. for the CORRECT payerID.
$aseco->console('>> Updating `hetimostfin` counts for all Players...');
$hetimostfin = array();
$line = 0;
$coppers = 3000;
$query = "
SELECT
`playerID`,
COUNT(`valami2`) AS `Count`
FROM `players_extra`
GROUP BY `playerID`;
";
$res2 = mysql_query($query);
if ($res2) {
if (mysql_num_rows($res2) > 0) {
while ($row = mysql_fetch_object($res2)) {
$hetimostfin[$row->playerID] = $row->Count;
}
foreach ($hetimostfin as $id => $count) {
$res2 = mysql_query("
UPDATE `players_extra`
SET `valami2` =(`valami2`+'".$coppers."')
WHERE `playerID` = ". $id ."
");
$line ++;
$coppers=($coppers-500);
if ($line >= 6) {
$coppers=500;
}
if ($line == 10){
break;
}
}
}
}
Try PDO. It's a much better and safer way of interacting with databases for PHP. http://php.net/manual/en/pdo.connections.php
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$hetimostfin = array();
$coppers = 3000;
$line = 0;
$query = <<<SQL
SELECT
playerID,
COUNT(valami2) AS `count`
FROM players_extra
GROUP BY playerID;
SQL;
foreach($dbh->query($query, PDO::FETCH_ASSOC) as $row) {
$hetimostfin[[$row['playerID']] = $row['count'];
// execute update statement
$line++;
}

How to make a dice roll UPDATE table data based on the roll result in php

i have a problem figuring out, how to roll the dice/s, so that the result/s will either do nothing or only UPDATE the selected users inventory.
<?php
if(isset($_SESSION['loggedin']))
{
include 'system/config.php';
//SESSION
$username = $_SESSION['loggedin'];
//selecting id from table users
$sql = "SELECT id FROM users WHERE username ='$username'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
//the user id from users
$user_id = $row['id'];
$sql = "SELECT user_id, size_kg, fish1, fish2, fish3, fish4, fish5, seaweed FROM inventory WHERE user_id='$user_id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$userId= $row['user_id'];
$fish1 = $row['fish1'];
$fish2 = $row['fish2'];
$fish3 = $row['fish3'];
$fish4 = $row['fish4'];
$fish5 = $row['fish5'];
$seaweed = $row['seaweed'];
//for debug
echo "$userId. id " . "$fish1 . fish1 <br>";
//$CatchProbability: dice roll for Catch Probability (ex: CatchProbability >= 30; echo You cought a $FishType(fish1, fish2, fish3, fish4, fish5, seaweed))
function rollcatch() {
return mt_rand(1,100);
}
echo rollcatch()." catch <br>";//for debug
//$FishType: dice roll for type of Fish (ex: $FishType(fish1) = 1-10 , $FishType(fish2) = 11-20, $FishType(fish4) = 31-40 $FishType(fish5) = 41-50, $FishType(seaweed) = 51-100)
function rolltype() {
return mt_rand(1,100);
}
echo rolltype()." type <br>";//for debug
function catchFish(){
if(rollcatch() < 30){
$rolltype = rolltype();
$result = "";
if($rolltype > 0 && $rolltype<10){
$result = "fish1";
}
else if($rolltype > 10 && $rolltype<=20){
$result = "fish2";
}
else if($rolltype > 20 && $rolltype<=30){
$result = "fish3";
}
else if($rolltype > 30 && $rolltype<=40){
$result = "fish4";
}
else if($rolltype > 40 && $rolltype<=50){
$result = "fish5";
}
else
{
$result="seaweed";
}
$sql = "UPDATE inventory SET $result = $result + 1 WHERE user_id='$userId'";
if(mysqli_query($conn, $sql)){
echo("You caught a $result");
}
}
else
{
echo("You caught nothing...");
}
}
catchFish(); //for debug
}
?>
Please, help me to debug, I get this error on successful catch:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ... on line 72
Line 72
<?
if(mysqli_query($conn, $sql)){
echo("You caught a $result");
}
?>
If I understood your question correctly:
if($CatchProbability <= 30) {
$FishType = rolltype();
if ($FishType <= 10) {
$sql = "UPDATE inventory SET fish1 = fish1 +1 WHERE user_id = '$userId'";
if(mysqli_query($conn, $sql))
{
echo " </br> You caught one Fish1.</br>";
}
}
echo 'You caught a '.$FishType.';
Not entirely sure I understood perfectly, but this code:
Checks if you caught a fish (30% chance)
Determines which fish you caught (10% chance for fish 1-5, 50% chance seaweed)
Adds 1 to the caught fish in the database
Outputs a message of which fish you caught
Hopefully this works for you
function catchFish(){
if(rollcatch() < 30){
$rolltype = rolltype();
$result = "";
if($rolltype > 0 && $rolltype<=10){
$result = "fish1";
}
else if($rolltype > 10 && $rolltype<=20){
$result = "fish2";
}
else if($rolltype > 20 && $rolltype<=30){
$result = "fish3";
}
else if($rolltype > 30 && $rolltype<=40){
$result="fish4";
}
else if($rolltype > 40 && $rolltype<=50){
$result="fish5";
}
else
{
$result="seaweed";
}
$sql = "UPDATE inventory SET $result = $result + 1 WHERE user_id='$user_id'";
if(mysqli_query($conn,$sql)){
echo("You caught a $result.");
}
}
else
{
echo("You caught nothing...");
}
}

Paging and query string for individual post MsSQL & PHP

I have written a paging script to page all the posts in my blog. Now I would like to create and endpoint such that I can go to mydomain/index.php?blogID1, mydomain/index.php?blogID2, mydomain/index.php?blogID3, mydomain/index.php?blogID4, etc.
Where can I read about doing this, and how do I implement it the easiest way possible, given my current script:
<?php
$rowsPerPage = 2;
try
{
$conn = new PDO( "sqlsrv:server=localhost ; Database=blog", "******", "*******");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(Exception $e)
{
die( print_r( $e->getMessage() ) );
}
try
{
$tsql = "SELECT COUNT(blogID) FROM blog_posts";
$stmt = $conn->query($tsql);
$rowsReturned = $stmt->fetch(PDO::FETCH_NUM);
if($rowsReturned[0] == 0)
{
echo "No rows returned.";
}
else
{
$numOfPages = ceil($rowsReturned[0]/$rowsPerPage);
for($i = 1; $i<=$numOfPages; $i++)
{
$pageNum = "index.php?pageNum=$i";
print("<a href='$pageNum' class='btn btn-primary active btn-sm'>$i</a> ");
}
}
$tsql = "SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY blogID DESC)
AS RowNumber,
blog_title,
blog_post,
blog_author,
blog_category,
blog_date,
blogID
FROM blog_posts)
AS Temp
WHERE RowNumber BETWEEN ? AND ?";
$stmt2 = $conn->prepare($tsql);
if(isset($_GET['pageNum']))
{
$highRowNum = $_GET['pageNum'] * $rowsPerPage;
$lowRowNum = $highRowNum - $rowsPerPage + 1;
}
else
{
$lowRowNum = 1;
$highRowNum = $rowsPerPage;
}
$params = array(&$lowRowNum, &$highRowNum);
$stmt2->execute(array($lowRowNum, $highRowNum));
while($row = $stmt2->fetch(PDO::FETCH_NUM) )
{
echo "$row[1]";
echo "$row[2]";
echo "$row[3]";
echo date_format( new DateTime($row['5']), 'd M Y, H:i' );
echo "$row[4]";
echo "$row[6]";
}
}
catch(Exception $e)
{
die( print_r( $e->getMessage() ) );
}
?>
Is row a post?
You can order your rows by any column, then limit the number of results and set an offset depending which page was requested.
Here's about mysql that endpoint: MySQL Data - Best way to implement paging?
For example if page is requested like this: index.php?pageNum=15 and you are showing 5 posts per page,
Grab that value with $page = $_GET['pageNum'] and set your PDO prepared statements for result number and offset (LIMIT).
Declare $resultsPerPage = 5
SELECT *
FROM Posts
LIMIT :offset, :maxResults
And push in those prepared statements:
offset --> ($page - 1) * $resultsPerPage
maxResults --> $resultsPerPage

Confused with PHP While Loop

I have the following output:
12345: 1
1234: 7
1234: 7
1234: 6
1234: 4
It is produced from a URL which ends in "?id=12345". What's supposed to happen is that the id is incremented by 1 when the id exists in the database or it is added when it doesn't. The last result produced by 1234 is right, but how do I stop the previous results of 1234 from being produced?
while ($row = $database->row()->fetch()) {
$id = $row["id"];
$count = $row["count"];
if ($id != $_GET["id"]) {
$insert = new MySQLConnect();
$insert->query("INSERT INTO links VALUES (:id, 1);");
$insert->run(array("id" => $_GET["id"]);
} elseif ($id == $_GET["id"]) {
$update = new MySQLConnect();
$update->query("UPDATE links SET count=count + 1 WHERE id=:id;");
$update->run(array("id" => $_GET["id"]);
}
}
EDIT:
function display_data()
{
$display = new MySQLConnect();
$display->query("SELECT * FROM links;");
$display->run();
while ($row = $display->row()->fetch()) {
$id = $row["id"];
$count = $row["count"];
$GLOBALS["output"] .= $id . ": " . $count . "<br/>";
}
}
You don't need the "while" if you just want to create/update the ID sent as parameter
$useId = (int)$_GET["id"];
$insert = new MySQLConnect();
$insert->query("INSERT INTO `links` (`id`, `count`) VALUES ('$useId', 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1");
$insert->run();

mysqli setting next and previous button using id

I would like to make a previous and next button to scroll through the database using ID. This is my code when I am still using mysql. Right now it is changed to mysqli so I have no idea whether this code still works or not, because I keep getting null.
function getNavID($id) {
$result4= mysqli_query("SELECT
( SELECT id FROM products_list
WHERE id > '$id' LIMIT 1 ) AS nextValue,
( SELECT id FROM products_list
WHERE id < '$id' ORDER BY id DESC LIMIT 1 ) AS prevValue
FROM products_list
LIMIT 1");
if ($resultID = mysqli_fetch_array($result4)) {
return $resultID;
}
else {
return NULL;
}
}
$LinkID = getNavID($id);
if (!is_null($LinkID['prevValue']))
{
?>
Previous
<?php
}
else if (!is_null($LinkID['nextValue']))
{
?>
Next
<?php
}
else
{
echo "No Entries";
}
Besides changing mysql_query to mysqli_query, is there anything that I need to change too? Thanks in advance for the help!
try this :
global $pdo;
$id = $the_selected_id;
$stmt_a = $pdo->prepare("
(SELECT * FROM images WHERE id < ? ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MAX(id) FROM images)) LIMIT 1");
$stmt_b = $pdo->prepare("
(SELECT * FROM images WHERE id > ? ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MIN(id) FROM images)) LIMIT 1");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute(array( (int)$id ));
$next = $stmt_b->execute(array( (int)$id ));
if ($stmt_a->rowCount() > 0) {
while($row = $stmt_a->fetch(PDO::FETCH_ASSOC)) {
echo 'Previous';
}
} else {
echo 'no previous';
}
if ($stmt_b->rowCount() > 0) {
while($row = $stmt_b->fetch(PDO::FETCH_ASSOC)) {
echo 'Next';
}
} else {
echo 'no next';
entre your db conection befor sentax like this:
<?
//enter your MySQL database host name, often it is not necessary to edit this line
$db_host = "localhost";
//enter your MySQL database username
$db_username = "your user name";
//enter your MySQL database password
$db_password = "your passwor";
//enter your MySQL database name
$db_name = "your db name";
//URL to the the site
$ScriptPath = "http://www.your-site.com/";
$db = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error($db));
mysqli_select_db($db, $db_name) or die("Error " . mysqli_error($db));
function getNavID($id) {
$result4= mysqli_query($db, "SELECT
( SELECT id FROM products_list
WHERE id > '$id' LIMIT 1 ) AS nextValue,
( SELECT id FROM products_list
WHERE id < '$id' ORDER BY id DESC LIMIT 1 ) AS prevValue
FROM products_list
LIMIT 1");
if ($resultID = mysqli_fetch_array($db, $result4)) {
return $resultID;
}
else {
return NULL;
}
}
$LinkID = getNavID($id);
if (!is_null($LinkID['prevValue']))
{
?>
Previous
<?php
}
else if (!is_null($LinkID['nextValue']))
{
?>
Next
<?php
}
else
{
echo "No Entries";
}
?>

Categories