get specific columms and compare values php - php

Hi I want to compare two values from two colummns but it doesnt work correctly. Do I need to cast the results and what I am doing wrong?
$query = "SELECT `columm1`, `columm2` FROM `table` WHERE `id` = ? ";
$stmt = $conn->prepare($query);
$stmt->bindParam(1,$eventID);
$stmt->execute();
$currentJoin = (int) $stmt->fetchColumn();
$maxParticipants = (int) $stmt->fetchColumn(1);
if($currentJoin >= $maxParticipants){
return;
}
else{

Warning There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data. - fetchColumn()
You can use fetch() instead
$stmt->execute();
$result = $stmt->fetch();
if($result[0] >= $result[1] ){
// ...
}

Related

How to return true or false if row exist on mysql via PDO [duplicate]

I want to have a condition that will perform some action when the row doesn't exist at all.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
Tried if (count($row) == 0) and if($stmt->rowCount() < 0) but none of them works.
You can just check the return value directly.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( ! $row)
{
echo 'nothing found';
}
/*
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here
if( ! $rows)
{
echo 'nothing found';
}
*/
If you are asking about checking without fetching then simply have MySQL return a 1 (or use the COUNT() command).
$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1';
//$sql = 'SELECT COUNT(*) from table WHERE param = ?'; // for checking >1 records
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
if($stmt->fetchColumn()) echo 'found';
if($stmt->rowCount() == 0)
should work fine, since the number of rows can't be less than zero in any event at all.
From the manual:
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.
I would suggest reading up on that here.
Heres what I use in my object classes:
function exists_by_id () {
// check if object exists by id
$stm = DB::$pdo->prepare('select count(*) from `table` where `column`=:column');
$stm->bindParam(':column', $this->column);
$stm->execute();
$res = $stm->fetchColumn();
if ($res > 0) {
return true;
}
else {
return false;
}
}

Sum multiuple columns

I have numbers stored in my MySQL (paid). I need to SUM the columns.
$sql= "SELECT SUM(furniture) FROM paid";
$stmt = $connect->prepare($sql);
$stmt->execute();
$furniture = (int) $stmt->fetchColumn();
$sql= "SELECT SUM(groceries) FROM paid";
$stmt = $connect->prepare($sql);
$stmt->execute();
$groceries = (int) $stmt->fetchColumn();
//so on....
There are morthan 50 columns in the database. My question is, Is there a shorter way to write this so I can get the SUM for each column and assign it to a variable?
Try with single query
$sql = "SELECT SUM(`furniture`) AS sumFurniture,
SUM(`groceries`) AS sumGroceries ,
...
FROM `paid` ";
result can be get with
$sth = $connect->prepare($sql);
$sth->execute();
$result = $sth->fetch();
$sumFurniture = $result['sumFurniture'];
$sumGroceries = $result['sumGroceries'];
....
You can combine them as a Single SQL Query
SELECT SUM(furniture) AS furniture, SUM(groceries) AS groceries....... FROM paid
If your where clause is same you can combine the query like this:
select sum(<column_name1>) column_name1,sum(<column_name2>) column_name2 from tablename where <where>
From php, you can fetch it: using array index "column_name1","column_name2"

updating the data using implode in php

please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}

SELECT and INSERT/UPDATE within the same query using mysqli

I am wandering if it is possible to first SELECT and if not true INSERT into db within the same query using mysqli?
Here is how I do i now:
$sel_timestamp = mktime(0, 0, 0, date("n"), date("j")-$day, date("Y"));
$sel_tag = date("Y-m-d",$sel_timestamp);
$user = 1;
if ($result = $mysqli->query("SELECT * FROM ".$prefix."_active_users WHERE userid = $user AND DATE(timestamp) = '$sel_tag'")){
if($result->num_rows < 1){
$insert = "INSERT INTO ".$prefix."_active_users (userid,timestamp) VALUES (?,?)";
$stmt = $mysqli->stmt_init();
if($stmt->prepare($insert)){
$stmt->bind_param('is', $user,$sel_tag);
$stmt->execute();
$stmt->close();
}
}
$result->close();
}
In my case I use 2 queries, but is it possible to merge this into one?
Thanks in advance!
if you have a UNIQUE KEY on (userid,timestamp), then you can use
INSERT IGNORE INTO ".$prefix."_active_users (userid,timestamp) VALUES (?,?)
IGNORE is a key word
However, you can leave your current code as is. Nothing wrong with having 2 queries too.

How to check if a row exist in the database using PDO?

I want to have a condition that will perform some action when the row doesn't exist at all.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
Tried if (count($row) == 0) and if($stmt->rowCount() < 0) but none of them works.
You can just check the return value directly.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( ! $row)
{
echo 'nothing found';
}
/*
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here
if( ! $rows)
{
echo 'nothing found';
}
*/
If you are asking about checking without fetching then simply have MySQL return a 1 (or use the COUNT() command).
$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1';
//$sql = 'SELECT COUNT(*) from table WHERE param = ?'; // for checking >1 records
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
if($stmt->fetchColumn()) echo 'found';
if($stmt->rowCount() == 0)
should work fine, since the number of rows can't be less than zero in any event at all.
From the manual:
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.
I would suggest reading up on that here.
Heres what I use in my object classes:
function exists_by_id () {
// check if object exists by id
$stm = DB::$pdo->prepare('select count(*) from `table` where `column`=:column');
$stm->bindParam(':column', $this->column);
$stm->execute();
$res = $stm->fetchColumn();
if ($res > 0) {
return true;
}
else {
return false;
}
}

Categories