Using Select and Update in PHP query - java

I am new to php .. anyway I have an application that require to provide the vacation information from the database to the supervisor and then allow the supervisor to enter his approval of this vacation ,
To do this, I use 2 php pages:
one to retrieve the employee vacation request information
and the other to insert the supervisor approval into the database
I want the application to insert this approval value in the record of this employeeID that I retrieve his information in this application.
The retrieval of employee information is done correctly, but the insert doesn't work !
I try this query but it didn't work (it didn't return any results when I exceute the query):
<?php
if(! $conn)
{
die('Could not connect: '.mysql_error());
}
mysql_select_db("a2202757_OURDATA",$conn);
$flag['code']=0;
if($r = mysql_query ("UPDATE request_vacation SET VacationApprove='".$_POST['Approval']."' WHERE IDEmployee=$id",$conn));
{
$flag['code']=1;
}
print(json_encode($flag));
mysql_close($conn);
?>
What is the problem ?

What happens is that you assign a variable ( = is an assignment for comparison you use == or ===) in an if statement.
When you want to check and assign at the same time use this:
if(false !== $r = $mysql_query("UPDATE .......") {
echo 'Update successfull';
}
else {
echo 'Update failed with error ' . mysql_error();
}

It is difficult to solve the problem if you do not provide any error message about the database connection. Please use the following code and using your host and username password to let php to print out the error message. It would be useful if you can provide further error information.
$conn = mysql_connect('localhost','username','password');
if(! $conn)
{
die('Could not connect: '.mysql_error());
}
$db_selected = mysql_select_db("a2202757_OURDATA",$conn);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$flag['code']=0;
$r = mysql_query ("UPDATE request_vacation SET VacationApprove='".$_POST['Approval']."' WHERE IDEmployee=$id",$conn);
if (!$r) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
if($r != null);
{
$flag['code']=1;
}
print(json_encode($flag));
mysql_close($conn);

Try this
<?php
if (isset ( $_POST ['Approval'] )/* && isset ( $_POST ['IDEmployee'] )*/) {
mysql_connect ( 'server', 'username', 'password' ) or die ( mysql_error () );
mysql_select_db ( 'a2202757_OURDATA' );
// mysql_query ( "UPDATE request_vacation SET VacationApprove='" . $_POST ['Approval'] . "' WHERE IDEmployee= '" . $_POST ['IDEmployee'] . "'" ) or die ( mysql_error () );
// Hey, What is $id, I leave it up to you.
mysql_query ( "UPDATE request_vacation SET VacationApprove='" . $_POST ['Approval'] . "' WHERE IDEmployee= '" . $id . "'" ) or die ( mysql_error () );
if (mysql_affected_rows () != - 1) {
// some rows has affected
echo mysql_affected_rows () . 'rows has affected';
} else {
// No row has affected
}
} else {
die ( 'Approval '/* . 'and/or IDEmployee'*/ . ' are not properly set' );
}
?>
and, please give some more detail

I think your code formatting is somehow broken on stackexchange.
Below is an example of how to use queries, because you code seems to be fairly broken and nonsense.
Attention: Don't use that in a production environment because it includes some SQLInjection vulnerabilities.
$id = $_POST["IDEmployee"];
// this sets the VacationApprove clumn of request_vacation
// to the $_POST['Approval'] variable where IDEmployee matches
// the previously selected $id
$insRes = mysql_query("UPDATE request_vacation SET VacationApprove = '".$_POST['Approval']."' WHERE IDEmployee = '".$id."'")
I don't know what you are trying to achieve. Please be more specific about your problem.

Related

PHP: Insert separated comma string value with as multiple array value Into MySql

Here is my goal
1. I have only one ID send from the server with list of string separated comma
this how it look like: ID=1, names=blue,red,green,yellow
2. This is my attempt:
2.1 i try to change the names to arrays by using this code
$myString = "Red,Blue,Black";
$myArray = explode(',', $myString);
2.2 and i try my insertion like this:
$sql="INSERT INTO `cat_interest`(`id`,`categories`) VALUES (1,'".$myArray["categories"]."'";
if (!$result = $mysqli->query($sql)){
$message = array('Message' => 'insert fail');
echo json_encode($message);
}else{
$message = array('Message' => 'new record inserted');
echo json_encode($tempArray);
}
Here is my complete code view
<?php
define('HOST','serveraddress');
define('USER','root');
define('PASS','pass');
define('DB','dbname');
ini_set('display_errors',1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$mysqli = new mysqli(HOST,USER,PASS,DB);
$message= array();
$myString = "Red,Blue,Black";// incoming string comma names
$myArray = explode(',', $myString);
$sql="INSERT INTO `cat_interest`(`id`,`categories`) VALUES (1,'".$myArray["categories"]."'";
if (!$result = $mysqli->query($sql)){
$message= array('Message' => 'insertion failed');
echo json_encode($message);
}else{
$message= array('Message' => 'new record inserted');
echo json_encode($message);
} ?>
This is what i want to achieve below
TABLE
ID Categories
1 RED
1 Blue
1 Black
after insertion
Please help i don't know what i doing wrong
While that SQL is invalid, you never close the values. Explode also doesn't build an associated array.
A rough example of how you could build a valid SQL statement would be
$myString = "Red,Blue,Black";// incoming string comma names
$myArray = explode(',', $myString);
print_r($myArray);
$sql = "INSERT INTO `cat_interest`(`id`,`categories`) VALUES";
foreach($myArray as $value){
$sql .= " (1, '{$value}'),";
}
$sql = rtrim($sql, ',');
Demo: https://eval.in/587840
When in doubt about how an array in constructed use print_r or var_dump. When having an issue with a query in mysqli use error reporting, http://php.net/manual/en/mysqli.error.php.
Also in your current usage you aren't open to SQL injections but if $myString comes from user input, or your DB you could be. You should look into using parameterized queries; http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.

PHPRunner: email array , can't personalize message

I’m using PHPRunner and I'm trying to create a button to send an email to selected users with personalized body message. I found an example in PHPRunner support page (Send an email to selected users) but it is only with an hardcoded message, so I’m trying to modify the example.
I managed to send correctly the email with personalized message if I only select one user, but if I select more than one all of them will receive the same message.
This is what I have now:
$emails = array();
while( $data = $button->getNextSelectedRecord() )
{
if( $data["EMAIL_FIELD"] )
$emails[] = $data["EMAIL_FIELD"];
$body = $data["MESSAGE_FIELD"];
}
// send the email
$email = implode(", ", $emails);
$subject = "";
$arr = runner_mail(array('to' => $email, 'subject' => $subject, 'body' => $body));
$result["txt"] = "Email were sent.";
// if error happened print a message on the web page
if( !$arr["mailed"] )
{
$errmsg = "Error happened: <br>";
$errmsg.= "File: " . $arr["errors"][0]["file"] . "<br>";
$errmsg.= "Line: " . $arr["errors"][0]["line"] . "<br>";
$errmsg.= "Description: " . $arr["errors"][0]["description"] . "<br>";
$result["txt"] = $errmsg;
}
What should I change? Thank you.
Problem:
In the foreach loop you are appending every new email address to one variable:
$emails[] = $data["EMAIL_FIELD"];
and you are assigning new value to $body variable (overriding the old one) in each iteration:
$body = $data["MESSAGE_FIELD"];
Therefore when you are calling runner_mail just once outside of the while loop, you will send same body (from the last iteration) to all recipients (you built an array of all recipients using while loop).
Solution:
You need to call runner_mail for each recipient (as the body is different). You can achieve it by moving the call to runner_mail inside the while loop:
while( $data = $button->getNextSelectedRecord() )
{
// Send only if email field not empty
if( $data["EMAIL_FIELD"] ) {
// This no longer should be an array of emails
$email = $data["EMAIL_FIELD"];
$body = $data["MESSAGE_FIELD"];
$subject = "";
// Email will be sent for each record
$arr = runner_mail(array('to' => $email, 'subject' => $subject, 'body' => $body));
}
}

Multiple values from a SQL Database in php through to Java as separate variables

I'm attempting to retrieve multiple values from a database through php to my android java in eclipse.
I'm managing to get all variations of json arrays except the one i need.
My database is:
**Aircraft** **Status**
A870_870 1
A870_871 1
A870_872 1
A870_873 1
A870_874 1
A870_875 1
A870_876 2
A870_877 1
A870_878 2
A870_879 2
A870_880 2
A870_881 0
A870_882 0
A870_883 0
A870_884 0
A870_885 0
The format I need so that my android app reads it is:
{"A70_870":"1","A70_871":"1","A70_872":"1","A70_873":"1","A70_874":"1",
"A70_875":"1","A70_876":"2","A70_877":"1","A70_879":"2","A70_878":"2",
"A70_880":"2","A70_881":"0","A70_882":"0","A70_883":"0","A70_884":"0",
"A70_885":"0"}
I've been attempting different 'while' loops all sorts of other variations and manage to get all sorts of combinations except the one i need. Surely there is a way...?
My closest PHP attemp is below:
<?php
$con = mysqli_connect("localhost","root","", "mytestdatabase");
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status");
$row = mysqli_fetch_row($userdetails) ;
$result_data = array(
'A70_870'=>$row[1],
'A70_871'=>$row[1],
'A70_872'=>$row[1],
'A70_873'=>$row[1],
'A70_874'=>$row[1],
'A70_875'=>$row[1],
'A70_876'=>$row[1],
'A70_877'=>$row[1],
'A70_879'=>$row[1],
'A70_878'=>$row[1],
'A70_880'=>$row[1],
'A70_881'=>$row[1],
'A70_882'=>$row[1],
'A70_883'=>$row[1],
'A70_884'=>$row[1],
'A70_885'=>$row[1],);
echo json_encode($result_data);
?>
It gives the correct format, but obviously only reads row 1. I can't access 3,5,7 etc..
If anyone can assist me in this it would be great!! :) I'm sure its something simple I'm not doing right....
I might be missing something but is it not just wrapping result extraction in a while loop:
$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status");
$result_data = array();
if ($userdetails) {
while($row = mysql_fetch_array($userdetails)) {
// $row[0] being aircraft and $row[1] being status
array_push($result_data , $row[0], $row[1]);
}
}
else {
echo mysql_error();
}
echo json_encode($result_data);
My PHP is very rusty, so might need adjustments. Hope this gets you on the way.

MySQL insert then update table data

Hey Ive run into a little problem in my SQL/PHP/JAVA application Im hoping you guys can help :)
I have a java application that when run is connected to my website when the java application validates that it is running it talks to my website and my website assigns a session Id to both the java application and the website itself.
cool we good so far?
alright my java application sends data at regular intervals to a page called Dashboard.php what I would like to do is save the data into my Mysql table then when new data is received by Dashboard.php from my java application where the sessionID is the same I would like the table to update to the new data that was just received
here is the php i have so far although it doesnt work.
function update($script_name, $version, $runtime, $status, $ranged, $attack, $defense, $strength, $magic, $sessionID, $username)
{
global $db;
$sql = "SELECT * FROM Dashboard WHERE session_id = '$sessionID'";
try {
$results = $db->query($sql);
if ($results->rowCount() <= 0) {
$query = "INSERT INTO Dashboard (script_name, version, runtime, status, ranged, attack, defense, strength, magic, session_id, username) VALUES ('$script_name', '$version', '$runtime', '$status', '$ranged', '$attack', '$defense', '$strength', '$magic', '$sessionID', $username)";
$db->exec($query);
} else {
foreach ($results as $row) {
$timerunnew = $row['runtime'] + $runtime;
$v4new = $row['ranged'] + $range;
$v5new = $row['attack'] + $attack;
$v6new = $row['defense'] + $defense;
$v7new = $row['strength'] + $strength;
$v8new = $row['magic'] + $magic;
}
$db->exec("UPDATE Dashboard SET `runtime` = $timerunnew, `ranged` = $v4new, `attack` = $v5new, `defense` = $v6new, `strength` = $v7new, `magic` = $v8new WHERE session_id = '$sessionID'");
}
} catch (PDOException $ex) {
echo "fail";
}
}
Ive also tried experimenting with ON DUPLICATE KEY UPDATE value = VALUES(value) however I have had no luck does anyone have a solution? any help would be much appreciated
If this is the only way that records can be inserted into the Dashboard table, then it is impossible for two records to share the same session_id (save for a race hazard occurring between the SELECT and INSERT commands). In which case, you should:
Ensure that there is a UNIQUE key defined on session_id:
ALTER TABLE Dashboard ADD UNIQUE KEY (session_id);
Use INSERT ... ON DUPLICATE KEY UPDATE, ideally with a properly parameterised prepared statement:
$qry = $db->prepare('
INSERT INTO Dashboard (
script_name, version, runtime, status, ranged, attack,
defense, strength, magic, session_id, username
) VALUES (
:script_name, :version, :runtime, :status, :ranged, :attack,
:defense, :strength, :magic, :session_id, :username
) ON DUPLICATE KEY UPDATE
runtime = runtime + VALUES(runtime),
attack = attack + VALUES(status),
defense = defense + VALUES(defense),
strength = strength + VALUES(strength),
magic = magic + VALUES(magic)
');
$qry->execute([
':script_name' => $script_name,
':version' => $version,
':runtime' => $runtime,
':status' => $status,
':ranged' => $ranged,
':attack' => $attack,
':$defense' => $defense,
':strength' => $strength,
':magic' => $magic,
':session_id' => $sessionID,
':username' => $username
]);

Whitespaces in Java/PHP

Spaces not changing to underscored when sent from Java-->PHP-->SQL
Java code:
String urlString = "http://www.mysite.com/auth/verifyuser.php?name="+name.toLowerCase().replace(" ","_");
PHP code:
$name = mysql_real_escape_string($_GET['name']);
$name = str_replace(' ', '_', $name);
$query = "select * from authinfo where name LIKE '$name'";
mysql_query($query);
$num = mysql_affected_rows();
if ($num > 0) {
echo '1';
} else {
echo '0';
}
when I implement a test log on the SQL database, it somehow still seems to show up with spaces instead of underscores(even though I replace it in Java and PHP) and the PHP file returns '0' rather than '1'. I've heard the issue might be whitespaces? It seems to happen to only certain users, mostly mac users.
If your php file is returning a 0, that means your query is not getting executed. Where are you establishing a connection with the database before executing the query?
Remark: where name = '$name'
mysql_affected_rows concerns INSERT, UPDATE and DELETE.
$r = mysql_query($query);
$num = mysql_num_rows($r);
It's unsafe to pass raw name into URL without encoding it.
String urlString = "http://www.example.com/auth/verifyuser.php?name=" + URLEncoder.encode(name.toLowerCase(), "UTF-8");
In PHP you can obtain data:
$name = urldecode($_GET['name']);

Categories

Resources