Check if empty not working for me - php

I want to check if a row value from my database is NULL or empty so I did the following:
$existcheck = "
SELECT *
FROM snm_content";
$existcheckcon = $conn->query($existcheck);
$existcheck = $existcheckcon->fetch_assoc();
if((!empty($existcheck['plaats'])) AND (!empty($existcheck['straat']))){
echo 'vol';
}else{
$vultable = "
ALTER TABLE snm_content
ADD (straat varchar(255) NULL,
plaats varchar(255) NULL)";
$vultablecon = $conn->query($vultable);
$vultable = $vultablecon->fetch_assoc();
$updatetable = "
UPDATE snm_content
SET straat = '".$straatnaam."', plaats = '".$bedrijven['plaats']."'";
$updatetablecon = $conn->query($updatetable);
$updatetable = $updatetablecon->fetch_assoc();
}
But I get the following message:
There was an error running the query [Duplicate column name 'straat']
Both straat and plaats in snm_content are all filled with NULL.
So why does it get to the else statement if the values are NULL?
I should mention, this code is inside a while loop from another query.

You should check if the column exist not if column have a data so you have to do like this :
$existcheck = "DESC snm_content";
$existcheckcon = $conn->query($existcheck);
$existcheck = $existcheckcon->fetch_assoc();
if((!empty($existcheck['plaats'])) AND (!empty($existcheck['straat']))){
echo 'vol';
}else{
$vultable = "
ALTER TABLE snm_content
ADD (straat varchar(255) NULL,
plaats varchar(255) NULL)";
$vultablecon = $conn->query($vultable);
$vultable = $vultablecon->fetch_assoc();
$updatetable = "
UPDATE snm_content
SET straat = '".$straatnaam."', plaats = '".$bedrijven['plaats']."'";
$updatetablecon = $conn->query($updatetable);
$updatetable = $updatetablecon->fetch_assoc();
}

Related

How do I change a value in a column in a table when I add another table?

How do I change the row value of a column in a table when I add another table?
How do you ask for help?
I have two tables in the database
The first table is called Drug
It consists of three columns:
Sample Table I
// TABLE Drug
DROP TABLE IF EXISTS `Drug`;
CREATE TABLE IF NOT EXISTS `Drug` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`brId` text NOT NULL,
`nameDrug` text NOT NULL,
PRIMARY KEY (`id`)
)
The second table is named brand
Sample Table II
// TABLE brand
DROP TABLE IF EXISTS `brand`;
CREATE TABLE IF NOT EXISTS `brand` (
`idBrand` int(11) NOT NULL AUTO_INCREMENT,
`brandName` text NOT NULL,
`theUse` text NOT NULL,
PRIMARY KEY (`idBrand`)
)
What I need is when you add a row in the brand table, brId is updated in the Drug table to the new idBrand by id in the drug table that was sent
I've done the following code because it does not work
<?php
require_once('include/config.php');
$id = $_POST['id'];
$brandName = $_POST['brandName'];
$theUse = $_POST['theUse'];
$query = "INSERT INTO brand
(brandName,theUse)VALUES('".$brandName."','".$theUse."');";
$insertBrand = mysqli_query($con,$query);
if($insertBrand)
{
$updatDrug = "UPDATE `drug` SET `brId` = new.idBrand WHERE `id` = '".$id."' ;";
$resultEnd = mysqli_query($con,$updatDrug);
if($resultEnd){
$result = 'OK';
echo json_encode($result);
}else{
$resultno = 'NO';
echo json_encode($resultno);
}
}
mysqli_close($con);
?>
After the INSERT, use mysqli_insert_id as the value for brId.
$br = mysqli_insert_id($con);
$updatDrug = "UPDATE drug SET brId = :brid WHERE id = :id";
$stmt = $con->prepare($updatDrug);
$stmt->bind_param('ii', $br, $id);
$stmt->execute();
$stmt->close();
And please avoid SQL INJECTION
Try transaction commit, here is an example
<?php
$db = new mysqli("localhost","root","","test"); //连接数据库
$db->autocommit(false); //设置为非自动提交——事务处理
$sql1 = "INSERT INTO `test`.`test1` (`name` )VALUES ('1' )";
$result1 = $db->query($sql1);
$sql2 = "INSERT INTO `test`.`test2` (`a` )VALUES ('1')";
$result2 = $db->query($sql2);
if ($result1 && $result2) {
$db->commit(); //全部成功,提交执行结果
echo '提交';
} else {
$db->rollback(); //有任何错误发生,回滚并取消执行结果
echo '回滚';
}
$db->autocommit(true);
$db->close();
?>

MYSQL: Insert variables into variable name table

I am trying to insert PHP variables in a mysql table, where the table name is also a variable, using mysqli_query. I've tried multiple solutions from stackoverflow but it still does not work.
I try to do it like this, maybe I am missing something. Thank you in advance!
<?php
session_start();
#include_once "modules/connections/dbconn.php";
$value = $_POST['value'];
$playerid = $_SESSION["steamid"];
$playername = fetchinfo("name","users","steamid",$playerid);
$playeravatar = fetchinfo("avatar","users","steamid",$playerid);
$playercoins = fetchinfo("coins", "users","steamid",$playerid);
if($playercoins - $value < 0){
die(json_encode(array('message' => 'ERROR', 'code' => "Not enough coins!")));
}
$game = fetchinfo("value","parameters","name","raffleRound");
$maxitems = fetchinfo("value","parameters","name","raffleMaxritems");
$items = fetchinfo("itemsnum","rafflegames","id",$game);
$itemname = "Coins";
$itemavatar = "images/creditcardicon.png";
$color = "D2D2D2";
$initialvalue = fetchinfo("value","rafflegames","id",$game);
$from = $initialvalue * 100;
$to = $from + $value * 100;
$tablename = 'rafflegame'.$game;
if($items < $maxitems){
mysqli_query($GLOBALS["connect"], "UPDATE rafflegames SET `value`=`value`+$value, `itemsnum`=`itemsnum`+1 WHERE `id`=$game");
mysqli_query($GLOBALS["connect"], "UPDATE users SET `coins`=`coins`-$value WHERE `steamid`=$playerid");
mysqli_query($GLOBALS["connect"], "INSERT INTO `" . $tablename . "` VALUES ('".$playerid."', '".$playername."','".$itemname."','".$color."','".$value."','".$playeravatar."','".$itemavatar."','".$from."','".$to."')");
}
else {
die(json_encode(array('message' => 'ERROR', 'code' => "Too many items in the current game")));
}
?>
The other two queries work just fine.
The table structure is this:
mysqli_query($GLOBALS['connect'],"CREATE TABLE `rafflegame$roundNumber` (
`id` int(11) NOT NULL auto_increment,
`userid` varchar(70) NOT NULL,
`username` varchar(70) NOT NULL,
`item` text,
`color` text,
`value` float,
`avatar` varchar(512) NOT NULL,
`image` text NOT NULL,
`from` int NOT NULL,
`to` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
mysqli_query($GLOBALS['connect'],"TRUNCATE TABLE `rafflegame$roundNumber`");
There is difference between table structure and insert column coumnt, When you want id column as auto incremented in that case column name should be included in insert query.
Please use the code as below:
<?php
session_start();
#include_once "modules/connections/dbconn.php";
$value = $_POST['value'];
$playerid = $_SESSION["steamid"];
$playername = fetchinfo("name","users","steamid",$playerid);
$playeravatar = fetchinfo("avatar","users","steamid",$playerid);
$playercoins = fetchinfo("coins", "users","steamid",$playerid);
if($playercoins - $value < 0){
die(json_encode(array('message' => 'ERROR', 'code' => "Not enough coins!")));
}
$game = fetchinfo("value","parameters","name","raffleRound");
$maxitems = fetchinfo("value","parameters","name","raffleMaxritems");
$items = fetchinfo("itemsnum","rafflegames","id",$game);
$itemname = "Coins";
$itemavatar = "images/creditcardicon.png";
$color = "D2D2D2";
$initialvalue = fetchinfo("value","rafflegames","id",$game);
$from = $initialvalue * 100;
$to = $from + $value * 100;
$tablename = 'rafflegame'.$game;
if($items < $maxitems){
mysqli_query($GLOBALS["connect"], "UPDATE rafflegames SET `value`=`value`+$value, `itemsnum`=`itemsnum`+1 WHERE `id`=$game");
mysqli_query($GLOBALS["connect"], "UPDATE users SET `coins`=`coins`-$value WHERE `steamid`=$playerid");
mysqli_query($GLOBALS["connect"], "INSERT INTO `" . $tablename . "`(`userid`,`username`,`item`,`color`,`value`,`avatar`,`image`,`from`,`to`) VALUES ('".$playerid."', '".$playername."','".$itemname."','".$color."','".$value."','".$playeravatar."','".$itemavatar."','".$from."','".$to."')");
}
else {
die(json_encode(array('message' => 'ERROR', 'code' => "Too many items in the current game")));
}
?>

mySQL->updating/inserting "compound" records

I have 2 tables structured like this:
CREATE TABLE `exp_ws_gk_text` (
`WGT_RID` INT(9) NOT NULL AUTO_INCREMENT,
`WGT_PRG_CODE` VARCHAR(5) NOT NULL,
`WGT_TEXT` VARCHAR(4000) NOT NULL,
INDEX `PrimaryKey` (`WGT_RID`)
)
CREATE TABLE `exp_ws_gk_state` (
`WGS_RID` INT(9) NOT NULL AUTO_INCREMENT,
`WGS_TYPE` INT(9) NOT NULL,
`WGS_STATE` VARCHAR(3) NOT NULL,
`WGS_WGT_RID` INT(9) NOT NULL,
INDEX `PrimaryKey` (`WGS_RID`),
INDEX `SecondaryKey` (`WGS_TYPE`, `WGS_STATE`)
)
This is how I query the data to be used in a site:
SELECT a.wgt_rid id, a.wgt_text text, a.wgt_prg_code prg_code,
b.wgs_state state, b.wgs_type type,
FROM exp_ws_gk_text a, exp_ws_gk_state b
WHERE a.wgt_rid = b.wgs_wgt_rid
I present the record with all the data returned. Now, when I want to edit or append a record, how would I save the data correctly if the data got sent from a form with these parameters:
$id = intval($_REQUEST['id']);
$prg_code = $_REQUEST['prg_code'];
$state = $_REQUEST['state'];
$crs_type = $_REQUEST['type'];
$text = $_REQUEST['text'];
An insert:
$sql = "BEGIN; ".
" INSERT INTO exp_ws_gk_text (WGT_PRG_CODE, WGT_TEXT) ".
" VALUES('".$prg_code."', '".$text."'); " .
" INSERT INTO exp_ws_gk_state (WGS_STATE, WGS_TYPE, WGS_WGT_RID) ".
" VALUES('".$state."', ".$course_type.", LAST_INSERT_ID()); ".
"COMMIT;";
$mysql_query($sql);
$sql = "SELECT WGS_WGT_RID id FROM exp_ws_gk_text WHERE WGS_RID = ".mysql_insert_id();
$result = mysql_query($sql);
$r = mysql_fetch_array($result, MYSQL_ASSOC);
echo json_encode(array(
'id' => $r["id"],
'prg_code' => $prg_code,
'state' => $state,
'type' => $type,
'text' => $text
));
A delete:
DELETE a, b FROM exp_ws_gk_text a
JOIN exp_ws_gk_state b ON a.WGT_RID = b.wgs_wgt_rid
WHERE a.WGT_RID = :id
$sql = "UPDATE exp_ws_gk_text a, exp_ws_gk_state b
SET a.WGT_PRG_CODE = ".$prg_code.", a.WGT_TEXT = ".$text.", b.WGS_STATE = ".$state.", b.WGS_TYPE = ".$crs_type."
WHERE
a.WGT_RID = ".$id." AND a.WGT_RID = b.wgs_wgt_rid";

MySQL update column only if value not empty where

I have an UPDATE query and using Ajax, I wanted to know if any value is empty can I only update the values that not empty in the database. I don't know if this is possible to have a if statement or something to check to skip the empty values. I know I can just add another form element but just wanted to know if there was another solution.
Only if the data is POST from front end form. If data not POST don't update this Title = '.$title .',
$id = $_POST['id'];
$title = "";
$description = $_POST['Description'];
$date = $_POST['Date'];
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = '.$title .',
`Description` = '.$description.',
`Date` = '.$date =.'
WHERE `id` = '.$id;
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
Update: This is what worked for me. Thanks Karim Daraf
$query = " UPDATE user SET
Title = Coalesce($title,Title ) etc...
Try it with Coalesce .
$query = " UPDATE user
SET
`Title` = CASE WHEN `Title`='' or `Title` IS NULL THEN '$title' END,
`Description` = CASE WHEN `Description`='' Or `Description` IS NULL THEN '$description' END,
`Date` = CASE WHEN `Date`='' Or Date` IS NULL THEN '$date' END
WHERE `id` = '".$id."' ";
or :
$query = " UPDATE user
SET
`id` = Coalesce('$id''".$id."' , NULLIF(`id`,'')),
`Title` = Coalesce('$title''".$title."',NULLIF(`Title`,'') ) ,
`Description` = Coalesce('$description''".$description."' , NULLIF(`Description`,'') ) ,
`Date` = Coalesce('$date''".$date."',NULLIF(`Date`,''))
WHERE `id` = '$id''".$id."' ";
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = COALESCE(NULLIF("'.$title.'", ""),`Title`),
`Description` = "'.$description.'",
`Date` = "'.$date.'"
WHERE `id` = "'.$id.'"';
Not sure to understand: you have data and want to update, but only if some fied in the DB are empty?
In the case perfom only a where:
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = '.$title .',
`Description` = '.$description.',
`Date` = '.$date =.'
WHERE `id` = '.$id.' AND Title = '';
for example

sql query error - logical or syntax

At the moment I am running an update query which is working, however it allows null values to be inserted which I don't want.
mysql_query('UPDATE community_table SET
age = "'.$age.'",
gender = "'.$gender.'",
pregnant = "'.$pregnant.'",
diet = "'.$diet.'",
smoker = "'.$smoker.'",
alcohol = "'.$alcohol.'",
exercise = "'.$exercise.'",
bmi = "'.$bmi.'",
sleeping = "'.$sleeping.'",
stress = "'.$stress.'",
education = "'.$education.'"
WHERE username = "' . $_SESSION['user'] . '" ');
I tried this query which seems to prevent null values being entered, however it also prevents values being entered when the variables are not null.
age = "'.$age.'",
gender = "'.$gender.'",
pregnant = "'.$pregnant.'",
diet = "'.$diet.'",
smoker = "'.$smoker.'",
alcohol = "'.$alcohol.'",
exercise = "'.$exercise.'",
bmi = "'.$bmi.'",
sleeping = "'.$sleeping.'",
stress = "'.$stress.'",
education = "'.$education.'"
WHERE age IS NOT NULL,
gender IS NOT NULL,
pregnant IS NOT NULL,
diet IS NOT NULL,
smoker IS NOT NULL,
alcohol IS NOT NULL,
exercise IS NOT NULL,
bmi IS NOT NULL,
sleeping IS NOT NULL,
stress IS NOT NULL,
education IS NOT NULL and where
username = "' . $_SESSION['user'] . '" ');
Is there something wrong with the above query, or do I perhaps have a null value in my input?
Thanks.
You can prevent empty string from being sent from your script or try this
UPDATE community_table SET
education = IFNULL($education, education) -- if null, maintain previous value
Just check values before insert like this -
UPDATE community_table SET
education = ifnull($education, education)

Categories