SELECT and INSERT/UPDATE within the same query using mysqli - php

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.

Related

get specific columms and compare values 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] ){
// ...
}

double data on mysql

I use the php operator && to select multiple data so that there is no duplication on mysql.
Does the code that I use below run fine? Is there a more simple use of PHP operators?
$date= date('Y/m/d');
$cekcount = mysql_num_rows(mysql_query("SELECT * FROM `pending_media` where `mediaid`='$dielz'"));
$cekcount2 = mysql_num_rows(mysql_query("SELECT * FROM `media` where `mediaid`='$dielz'"));
$selectcount = mysql_query("SELECT * FROM `media` where `date`='$date' AND `uplink`='$nam'");
$cekcount3 = mysql_num_rows($selectcount);
if($cekcount == 0 && $cekcount2 == 0 && $cekcount3 == 0){
mysql_query("INSERT INTO pending_media VALUES('','$nam','$dielz')");
Upgrade to mysqli, I'll recommend object-oriented syntax because it is nicer to work with.
In accordance with the best practice of "minimize calls to the database", I'll condense your three queries into a single, united SELECT call then check for a non-0 result.
My untested suggestion using mysqli's object-oriented syntax (I did test the SELECT query in PHPMyAdmin):
$query = "SELECT SUM(tally)
FROM (
SELECT COUNT(*) AS tally
FROM pending_media
WHERE mediaid = ?
UNION ALL
SELECT COUNT(*)
FROM media
WHERE mediaid = ? OR (date = ? AND uplink = ?)
) t";
$conn = new mysqli("localhost", "root","","dbname");
$stmt = $conn->prepare($query);
$stmt->bind_param("ssss", $dielz, $dielz, $date, $nam);
$stmt->execute();
$stmt->bind_result($tally);
$stmt->fetch();
if (!$tally) {
$stmt->close();
// insert qualifying data
$stmt = $conn->prepare("INSERT INTO pending_media VALUES ('',?,?)");
$stmt->bind_param("ss", $nam, $dielz);
if ($stmt->execute()) {
echo "Insert Query Error"; // $stmt->error;
}else{
echo "Success";
}
}

Php: fetching last inserted row on mysql table to use for another mysql statement

I need to fetch the id of the last inserted row from a mysql table using php and use that id to enter a new entry on another table. I have this until now
$inductionmethod = $_POST['inductionmethod'];
$injectionmethod = $_POST['injectionmethod'];
$dosage = $_POST['dosage'];
$metric = $_POST['metric'];
$notes = $_POST['notes'];
global $db_usr;
$query = "SELECT MAX( experiment_id ) FROM experiment";
$prep = $db_usr->prepare($query);
$lastid = $prep->fetch();
$query ="INSERT INTO experiment_using_methods (experiment_id, induction_method, injection_method, dosage_quantity, dosage_unit, dosage_qualitative)
VALUES (
'".$lastid['MAX( experiment_id )']."', # the fetched ID of the corresponding dataset
(SELECT induction_method_id FROM induction_method WHERE im_name = '".$inductionmethod."'), # name of induction method
(SELECT injection_method_id FROM injection_method WHERE im_name = '".$injectionmethod."'), # name of the injection method
'".floatval($dosage)."', # dosage quantity
'".$metric."', # dosage unit or metric
'".$notes."' # qualitative dosage - REMOVE??
)";
$prep = $db_usr->prepare($query);
$prep->execute();
I think I'm getting an error while fetching the MAX( experiment_id) or maybe I'm using it incorrectly on the INSERT statement because if I replace the ".$lastid['MAX( experiment_id )']." part by a number the insert statement works fine. On the other hand I also test the SELECT MAX( experiment_id ) FROM experiment statement on the mysql command line and it also works fine. Am I using fetch and referencing the result value correctly?
Thing this is the main issue:
$prep = $db_usr->prepare($query);
$lastid = $prep->fetch();
change it to:
$prep = $db_usr->prepare($query);
$prep->execute();
$lastid = $prep->fetch();
If you have connection as $con, then for MySQLi Object-oriented:
if ($con->query($sql) === TRUE) {
$last_id = $conn->insert_id;
}
MySQLi Procedural way:
if (mysqli_query($con, $sql)) {
$last_id = mysqli_insert_id($con);
}
PDO way:
$con->exec($sql);
$last_id = $con->lastInsertId();

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();
}

Categories