Check to see if any of inputs has value - php

Check to see if any of inputs has value? If input has the value null/empty don't update them to DB?
Here is my code and when I have empty input I lost previusly data in DB.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysql_host = "localhost";
$mysql_username = "root";
$mysql_password = "";
$mysql_database = "medvedgrad";
// First we create the connection
$pdo = new PDO("mysql:host=".$mysql_host .";dbname=".$mysql_database .";charset=utf8", $mysql_username, $mysql_password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = json_decode(file_get_contents("php://input"));
$zm = $data->zlatni_medvjed;
$ck = $data->crna_kraljica;
$gv = $data->gricka_vjestica;
$dk = $data->dva_klasa;
$fk = $data->fakin;
// Then we prepare, and execute the query
$stmt = $pdo->prepare("UPDATE `stanje_piva`
SET
`zlatni_medvjed`=`zlatni_medvjed`+:zm, `crna_kraljica`=`crna_kraljica`+:ck, `gricka_vjestica`=`gricka_vjestica`+:gv, `dva_klasa`=`dva_klasa`+:dk,`fakin`=`fakin`+:fk WHERE `id`=1");
$stmt->execute(array("zm" => $zm, "ck" => $ck, "gv" => $gv, "dk" => $dk, "fk" => $fk));
?>

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysql_host = "localhost";
$mysql_username = "root";
$mysql_password = "";
$mysql_database = "medvedgrad";
// First we create the connection
$pdo = new PDO("mysql:host=".$mysql_host .";dbname=".$mysql_database .";charset=utf8", $mysql_username, $mysql_password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = json_decode(file_get_contents("php://input"));
$zm = $data->zlatni_medvjed;
$ck = $data->crna_kraljica;
$gv = $data->gricka_vjestica;
$dk = $data->dva_klasa;
$fk = $data->fakin;
//Let's do like Jack the ripper, lets divide into parts :p
$updateparts = array();
$zm = trim($zm);
if($zm != "")
{
$zmpart = "`zlatni_medvjed`=`zlatni_medvjed`+:zm";
$updateparts[] = $zmpart;
}
$ck = trim($ck);
if($ck != "")
{
$ckpart = "`crna_kraljica`=`crna_kraljica`+:ck";
$updateparts[] = $ckpart;
}
$gv = trim($gv);
if($gv != "")
{
$gvpart = "`gricka_vjestica`=`gricka_vjestica`+:gv";
$updateparts[] = $gvpart;
}
$dk = trim($dk);
if($dk != "")
{
$dkpart = "`dva_klasa`=`dva_klasa`+:dk";
$updateparts[] = $dkpart;
}
$fk = trim($fk);
if($fk != "")
{
$fkpart = "`fakin`=`fakin`+:fk";
$updateparts[] = $fkpart;
}
$updatepartstring = implode(",",$updateparts);
$update_query="UPDATE `stanje_piva`
SET
$updatepartstring
WHERE `id`=1";
// Then we prepare, and execute the query
$stmt = $pdo->prepare($update_query);
$stmt->execute(array("zm" => $zm, "ck" => $ck, "gv" => $gv, "dk" => $dk, "fk" => $fk));
?>

Related

PHP: Loop returns only the first or last one

I use an XML request to get all the news from the database. So far good, but I always get back only the last or first value in my loop.
function SendData($pass) :void {
if($pass) {
$host = "Database_:3360";
$username = "root";
$password = "root";
$dbname = "db";
$dbquery = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$stmt = $dbquery->prepare("SELECT * FROM tab_news ORDER BY `date` DESC");
$stmt->execute();
$count = $stmt->rowCount();
if($count === 0){
$news[] = 'Es gibt noch keine News...';
} else {
$news = $stmt->fetchAll(PDO::FETCH_ASSOC)
}
}
echo json_encode(
array(
'allowed' => $pass,
'count' => $count,
'news' => $news
)
);
}
I try it now for 1h but do not get the desired result. What is wrong ?

Return list of strings with mysql query in PHP

I'm trying to make a simple query with PHP that returns a list of Strings with all the names of the users, but I can figure out how to do do it. The only thing i thought wa this:
<?php
$host_name = "hostname";
$database = "database";
$user_name = "username";
$password = "pass";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
$select = "SELECT username from userstasker";
$result = $connect->query($select);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$connect->close();
?>
But this returns a JSon, ant idea how to do it?
<?php
$host_name = "hostname";
$database = "database";
$user_name = "username";
$password = "pass";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
$select = "SELECT username from userstasker";
$result = $connect->query($select);
$usernames = array();
while($r = mysqli_fetch_assoc($result)) {
$usernames[] = $r["username"];
}
$connect->close();
// Do something with $usernames
?>

odbc_exec - no error or results

I'm new to using odbc functions. I'm trying to simply execute a simple query, but I get not error or results back. I'm not sure what's wrong.
$server = [hidden];
$database = [hidden];
$user = [hidden];
$password = [hidden];
$connection = odbc_connect("Driver={ODBC Driver 13 for SQL Server};Server=$server;Database=$database;", $user, $password);
if ($connection) {
$mail = 'email#email.com';
$queryc = "SELECT COUNT(*) AS [Found] FROM [Table].[dbo].[Persons] WHERE [Address] = '$mail'";
$resultsc = odbc_exec($connection, $queryc);
if( !$resultsc ) {
die( print_r( odbc_error())));
} else {
'hi!';
}
}
Figured out the problem. It was fixed doing this:
$server = [hidden];
$database = [hidden];
$user = [hidden];
$password = [hidden];
$connection = odbc_connect("Driver={ODBC Driver 13 for SQL Server};Server=$server;Database=$database;", $user, $password);
if ($connection) {
$mail = 'email#email.com';
$queryc = "SELECT COUNT(*) AS [Found] FROM [Table].[dbo].[Persons] WHERE [Address] = '$mail'";
$resultsc = odbc_exec($connection, $queryc) or die(odbc_errormsg());
if( $resultsc ) {
'hi!';
}
}

How to access a variable inside a function from a different file?

I have two files, a functions.php which contains a PDO object to connect to a database and contains columns as variables and a index.php to output the variable containing the data. the database connection works however when I try to echo a variable from my function it is returned undefined, What am i doing wrong;
functions.php
<? php
function connectDB() {
$hostname = 'xxxxxxxx';
$db = 'xxxxxxx';
$user = 'xxxxxxxx';
$pass = 'xxxxxxx';
$dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "//my query";
$query = $dbh->prepare($sql);
$query->execute(array('//value','//value'));
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $query->fetch()):
$var1 = $r['column1'];
$var2 = $r['column2'];
$var3 = $r['column3'];
$var4 = $r['column4'];
$var5 = $r['column5'];
endwhile;
}
?>
index.php
<?php
include 'functions.php';
?>
<?php
try {
connectDB();
echo 'You are connected to Database';
echo $var1;
$dbh = null;
}
catch(PDOException $e) {
echo $e -> getMessage();
}
?>
those variables are by default local to your connectDB() function, so you will have to either declare them in global scope beforehand, or use the $GLOBALS to set them:
Method 1
<? php
$var1 = '';
$var2 = '';
$var3 = '';
$var4 = '';
$var5 = '';
function connectDB() {
$hostname = 'xxxxxxxx';
$db = 'xxxxxxx';
$user = 'xxxxxxxx';
$pass = 'xxxxxxx';
$dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "//my query";
$query = $dbh->prepare($sql);
$query->execute(array('//value','//value'));
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $query->fetch()):
$var1 = $r['column1'];
$var2 = $r['column2'];
$var3 = $r['column3'];
$var4 = $r['column4'];
$var5 = $r['column5'];
endwhile;
}
?>
Method 2
<? php
function connectDB() {
$hostname = 'xxxxxxxx';
$db = 'xxxxxxx';
$user = 'xxxxxxxx';
$pass = 'xxxxxxx';
$dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "//my query";
$query = $dbh->prepare($sql);
$query->execute(array('//value','//value'));
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $query->fetch()):
$GLOBALS['var1'] = $r['column1'];
$GLOBALS['var2'] = $r['column2'];
$GLOBALS['var3'] = $r['column3'];
$GLOBALS['var4'] = $r['column4'];
$GLOBALS['var5'] = $r['column5'];
endwhile;
}
?>
Sincerely, your copy-paste-service :)
you can generally access variables in one of two ways, either as a parameter passed to the function or by declaring, within the function, the variable as global. Hope the following helps a little
function banana( $externalvar=false ){
echo $externalvar;
}
or
function banana(){
global $externalvar;
echo $externalvar;
}
The smart code should use yield keyword:
function connectDB() {
// ...
$output = [];
$index = 0;
while ($r = $query->fetch()):
yield $r;
endwhile;
}
Then:
foreach ($connectDB() as $row)
echo $row['column1'], PHP_EOL;
echo $row['column2'], PHP_EOL;
echo $row['column3'], PHP_EOL;
endforeach;
Otherwise, just return an array, then extract:
function connectDB() {
// ...
$output = [];
$index = 0;
while ($r = $query->fetch()):
++$index;
foreach($r as $key => $value) {
$output[$name . '_' . $index] = $value;
}
endwhile;
return $output;
}
Then:
$vars = connectDB();
extract($vars);
;
echo $column1_1, PHP_EOL;
echo $column2_1, PHP_EOL;
echo $column3_1, PHP_EOL;
;
echo $column1_2, PHP_EOL;
echo $column2_2, PHP_EOL;
echo $column3_2, PHP_EOL;
The second purpose is very ugly.

PHP Insert Query Using Prepare Statement

I have created an insert form. I'm doing an insertion operation into MySQL using prepare statement but it's not working. I don't understand what's wrong. Please help me to solve this issue. Is this what I did correct?
insert.php
<?php
include('dbconn.php');
session_start();
$_SESSION['example']='Session Created';
$srn = $_POST['srn'];
$client = $_POST['client']; // required
$category = $_POST['category'];
$sd = $_POST['sd']; // required
$fd = $_POST['fd'];
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
$sql = "Insert into main(client,category,sd,fd) values(:client,:category,:sd,:fd)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':client',$_POST['client'],PDO::PARAM_STR);
$stmt->bindParam(':category',$_POST['category'],PDO::PARAM_STR);
$stmt->bindParam(':sd',$_POST['sd'],PDO::PARAM_STR);
$stmt->bindParam(':fd',$_POST['fd'],PDO::PARAM_STR);
$stmt->execute();
?>
dbconn.php
<?php
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$mysqli = new mysqli($host,$user,$pwd,$db);
/* ESTABLISH CONNECTION */
if (mysqli_connect_errno()) {
echo "Failed to connect to mysql : " . mysqli_connect_error();
exit();
}
?>
Its always good to put up the errors you are having.
You are using two different database connection types pdo, and mysqli. You only need one.
I stripped your code down to the minimum.
<?php
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
//$srn = $_POST['srn'];
$client = $_POST['client']; // required
$category = $_POST['category'];
$sd = $_POST['sd']; // required
$fd = $_POST['fd'];
// make sure client and sd are set here
$stmt = $pdo->prepare("
INSERT INTO
main
(client,category,sd,fd)
VALUES
(:client,:category,:sd,:fd)
");
$success = $stmt->execute([
'client' => $client,
'category' => $category,
'sd' => $sd,
'fd' => $fd
]);

Categories