I am trying to create a PHP form using MySQL database.
I have created a dropdown list with the names of samples (like Al, Au...) and a textbox for the values.
My problem that the units are in my database sometimes in ppm, sometimes in pph.
How can I set if the values are in pph, use the $value=$_POST["value"]/10000;
if the values are in ppm, use $value=$_POST["value"]?
Any idea?
My code:
<?php
if (isset($_POST["sample"]))
{
$sample = $_POST["sample"];
$unit = mysql_query("SELECT unit FROM analysis where sample='" . $sample . "'");
if ($unit == 'pph')
{
$value = $_POST["value"] / 10000;
$sql = "SELECT
a.sample,
concat (a.modif, (IF (unit='pph',10000*value,value))),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
anlysis a,
sample b
WHERE
a.mkey=b.mkey AND sample = '$sample' AND value > '$value'";
$result = mysql_query($sql);
}
else
{
$value = $_POST["value"];
$sql = "SELECT
a.sample,
concat ( a.modif, ( IF (unit = 'pph', 10000 * value, value) ) ),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
anlysis a,
sample b
WHERE
a.mkey = b.mkey AND sample = '$sample' AND value > '$value'";
$result = mysql_query($sql);
}
}
Thank you!
Here's what I'd suggest:
<?php
if (isset($_POST["sample"])) {
$sample = htmlspecialchars(trim($_POST["sample"])); //A little clean-up wont hurt...
$unit = mysql_query("SELECT unit FROM analysis where sample='" . $sample . "'");
if ($unit == 'pph'){
$postVal= htmlspecialchars(trim($_POST["value"]));
$value = $postVal / 10000;
$sql = "SELECT a.sample,
concat (a.modif, (IF (unit='pph',10000*value, value))),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
analysis AS a
LEFT JOIN sample AS b
ON a.mkey=b.mkey
WHERE
a.sample='" . $sample . "' AND a.value > '" . $value ."'";
$result = mysql_query($sql);
}
else
{
$postVal= htmlspecialchars(trim($_POST["value"]));
$value = $postVal;
$sql = "SELECT
a.sample,
concat ( a.modif, ( IF (unit = 'pph', 10000 * value, value) ) ),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
analysis AS a
LEFT JOIN sample AS b
ON a.mkey=b.mkey
WHERE
a.mkey = b.mkey AND sample = '" . $sample . "' AND value > '" . $value . "'";
$result = mysql_query($sql);
}
first
$analysis = mysql_fetch_object($query);
then you can access the value
if ($analysis->unit == 'pph')
Related
I am building an android app that uses geo location. I am trying to improve my overall app to improve its smoothness while running. I am using volly to connect to a php page on my web sever where the php page can then access my phpmyadmin database. My php page for updating locations is a horrible mess and I was hoping it can be fixed with the right sql query.
Lets get down to it.
So I have a table named users
and a table named friends
In this particular example david is friends with mark and jack. Also to clarify mark and jack are friends with david.
What I need to do is Write a query if given a user ID say for example 3 that will produce a table of that person and his friends ID, cordsV1, cordsV2 without any duplicate IDs in the table.
I was able to get this to work with using loops and variables ect but as I said it is a horrible mess.
Here is my current all sql query attempt:
SELECT DISTINCT ID, cordsV1, cordsV2 FROM `friends`,`users` WHERE user_one_ID = 1 AND status = 1;
HOWEVER this just returns all of the user IDs from the user table. I am really bad with sql so if someone could point me in the right direction it would be much appreciated.
Here is my horrible mess of code if you were wondering:
<?php error_reporting(E_ALL | E_STRICT); ?>
<?php
$THIS_USER_ID = $_GET['THIS_USER_ID'];
try {
$one = 1;
$db = new PDO("");
$sql = "SELECT * FROM friends WHERE user_one_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "' OR user_two_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "'";
$rows = $db->query($sql)
->fetchAll(PDO::FETCH_ASSOC);
$printMe = [];
foreach($rows as $row){
$printMe[] = $row;
}
$jsonArr = json_encode($printMe);
$characters = json_decode($jsonArr, true);
// Getting the size of the sample array
$size = sizeof($characters);
$neg = -1;
$sql2 = "SELECT * FROM users WHERE ID = '" . $neg . "'";
$sql3 = "";
$sql4 = "";
for ($x = 0; $x < $size; $x++ ){
if ($characters[$x]['user_one_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1){
$hold = $characters[$x]['user_two_ID'];
$sql3 = $sql3 . " OR ID = '" . $hold . "'";
} else if($characters[$x]['user_two_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1) {
$hold = $characters[$x]['user_one_ID'];
$sql4 = $sql4 . " OR ID = '" . $hold . "'";
}
}
$sql5 = $sql2 . $sql3 . $sql4;
$sql7 = "SELECT * FROM users WHERE ID = '" . $THIS_USER_ID . "'";
$printMe2 = [];
$rows3 = $db->query($sql7)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows3 as $row3){
$printMe2[] = $row3;
}
$rows2 = $db->query($sql5)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows2 as $row2){
$printMe2[] = $row2;
}
$jsonArr2 = json_encode($printMe2);
echo $jsonArr2;
$db = null;
} catch(PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
?>
Get the user-data
SELECT
*
FROM
users
WHERE ID = ?
Get the user-data of friends
SELECT
users.*
FROM
friends
JOIN
users ON users.ID = friends.user_two_ID
WHERE
friends.user_one_ID = ?
Better use prepared statements, or your app wont be alive very long due to SQL-Injections.
You also want to have a look at meaningful names.
I am setting a variable that contains an array as a constraint to a SELECT sql statement. However the constraint seems only to apply to one piece of data in the array. Why is this?
Code below:
<?php
include 'connection.php';
$Date = $_POST['date'];
$Unavail = 0;
$Avail = 0;
$Availid = 0;
$low = 99999;
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
while($request = mysql_fetch_array($dayresult)) {
$Unavail = $request;
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance WHERE Username != '$Unavail[username]'";
$dayresult1 = mysql_query($query1);
while($request1 = mysql_fetch_array($dayresult1)) {
echo "<span>" . $request1['name'] . " is available.</br>";
if ($request1['work_stats']<=$low) {
$low = $request1['work_stats'];
$Availid = $request1['name'];
}}
echo "<span>" . $Availid . " is available on " . $_POST['date'] . " and is on workstat level " . $low . ".</span></br>";
?>
The output shows two names in the first echo but then shows one of those names as available in the second echo (these echos are only in place as part of my testing),
Many Thanks
The first query can have multiple results.
SELECT username FROM daysoff WHERE date = '$Date'
Let's say if gives two rows: Dave and John.
You're only keeping the last record so it will seem like Dave is available.
You should probably do something like:
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
$unavailable_users = array();
while($request = mysql_fetch_array($dayresult)) {
$unavailable_users[] = $request["username"];
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance
WHERE NOT Username IN ('" . implode("','", $unavailable_users) . "')";
// etc
Or in one go with a LEFT JOIN:
SELECT `Username`, `name`, `work_stats`
FROM `freelance`
LEFT JOIN `daysoff` ON `freelance`.`Username` = `daysoff`.`username`
AND `daysoff`.`date` = '$Date'
WHERE
`daysoff`.`username` IS NULL
I have a pdo command like this $sql = $pdoObj->execute($query) but it does not work, 0 result returning. I echo'ed out the $query variable just before calling execute() and then pasted it inside the execute() and the code ran successfully. I can't understand what is the problem here as I have done this in other parts of my code without problems.
Here are some examples of the queries:
SELECT s.id, s.marca, s.colore, s.prezzo, i.id_scarpa, i.taglia FROM scarpe AS s INNER JOIN info_scarpe AS i ON i.id_scarpa = s.id WHERE 1 = 1 AND taglia IN ('40','41','42') AND colore IN ('rosso', 'nero')
SELECT * FROM scarpe WHERE 1=1
SELECT * FROM scarpe WHERE 1=1 AND marca IN ('adidas','nike')
They are all dynamic generated queries based on the $_GET variable.
EDIT:
Sure
if ( isset($_GET) ) {
if ( isset($_GET['taglia']) ) {
$query = "
SELECT
s.id, s.marca, s.colore, s.prezzo, i.id_scarpa, i.taglia
FROM
scarpe AS s
INNER JOIN
info_scarpe AS i
ON i.id_scarpa = s.id
WHERE
1 = 1
";
foreach ( $_GET as $index => $val ) {
$a = explode(',', $val);
$in = "'" . implode("','", $a) . "'";
$query .= ' AND '.$index.' IN ('.$in.')';
}
} else {
$query = " SELECT * FROM scarpe WHERE 1=1";
foreach ( $_GET as $index => $val ) {
$a = explode(',', $val);
$in = "'" . implode("','", $a) . "'";
$query .= ' AND '.$index.' IN ('.$in.')';
}
}
echo 'data loaded';
} else {
$query = " SELECT * FROM scarpe ORDER BY id DESC ";
}
EDIT2:
I use query() and not execute() but still does not work
The arguments for execute should be an array with query parameters. You mean to use either
$result = $pdoObj->query($query);
OR
$stmt = $pdoObj->prepare($query);
$stmt->execute();
I am attempting to clean up a database table that might be missing book titles or bio information. The user is supposed to be able to click a button and the program does the rest.
I have run the query in my database and it returns the information I am looking for, so i think my issue is with the for each loop.
Here is my code:
<?php
require_once ('../db.php');
require_once ('../amazon/amazon.php');
$conn = db_connect();
session_start();
$x = 0;
// find all of the books with no Titles or Bios
$result = $conn->query("
select
i.date_created,
users.username,
i.sku,
i.isbn13,
i.quantity,
source.source,
i.date_process,
location.location
from inventory i
left join book on i.isbn13 = book.isbn13
left join source on i.source_id = source.source_id
left join location on i.location_id = location.location_id
left join users on i.created_by = users.user_id
where sku > '10000000'
and quantity >= 1
and (book.title = ''
or book.title is null
or book.author = ''
or book.author is null)
and i.isbn13 >1");
$num_rows = $result->num_rows;
if($num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$isbnArray[$x] = $row['isbn13'];
$qtyArray[$x] = $row['quantity'];
$x++;
} // end of while loop
$sum = array_sum($qtyArray);
for each ($isbnArray as $isbn)
{
//retrieve amazon data
$parsed_xml = amazon_xml($isbn);
$amazonResult = array();
$current = $parsed_xml->Items->Item;
if($parsed_xml->Items->Request->IsValid == 'True') {
$amazonResult = array(
'Title' => $current->ItemAttributes->Title,
'Author' => $current->ItemAttributes->Author,
'Edition' => $current->ItemAttributes->Edition,
'Weight' => ($current->ItemAttributes->PackageDimensions->Weight / 100),
'Publisher' => $current->ItemAttributes->Publisher,
'PublishDate' => $current->ItemAttributes->PublicationDate,
'Binding' => $current->ItemAttributes->Binding,
'SalesRank' => $current->SalesRank,
'ListPrice' => str_replace('$','',$current->ItemAttributes->ListPrice->FormattedPrice),
'ImageURL' => $current->LargeImage->URL,
'DetailURL' => $current->DetailPageURL
);
} // end of if statement
//update Title and Bio info in book table
$conn->query("
update book
set isbn13 = '$isbn',
author = '" . $amazonResult['Author'] . "',
title ='" . $amazonResult['Title'] . "',
edition = '" . $amazonResult['Edition'] . "',
weight = '" . $amazonResult['Weight'] . "',
publisher = '" . $amazonResult['Publisher'] . "',
binding = '" . $amazonResult['Binding'] . "',
listed_price = '" . $amazonResult['ListPrice'] . "',
pub_date = '" . $amazonResult['PublishDate'] . "'
WHERE isbn13 = '$isbn'");
} // end of for each loop
}
$message = array( 'message' => $sum.' Records were updated' );
$conn->close();
echo json_encode($message);
?>
To me everything looks right, but when I run it with firebug on, there is no message. Console.log(data) in my success function says empty string.
What am I doing wrong? Should I restructure my for each loop?
EDIT: I changed parts of the code to get an accurate count of how many records were updated. This is the $qtyArray[$x] = $row['quantity'] line. My console.log(data) shows that 2995 records were updated, but the #message does not appear on the screen, just the console.log(data). Hope this gives a little more insight.
Your error may lie in your while loop:
while($row = $result->fetch_assoc()) {
$isbnArray[$x] = $row['isbn13'];
$sum = array_sum($isbnArray);
} // end of while loop
$x is initialized to 0, and never changed, so you just overwrite the same entry in the array each time.
You have to change:
$isbnArray[$x] = $row['isbn13'];
to:
$isbnArray[] = $row['isbn13'];
You need to escape your " in your query
$result = $conn->query("
select
i.date_created,
users.username,
i.sku,
i.isbn13,
i.quantity,
source.source,
i.date_process,
location.location
from inventory i
left join book on i.isbn13 = book.isbn13
left join source on i.source_id = source.source_id
left join location on i.location_id = location.location_id
left join users on i.created_by = users.user_id
where sku > '10000000'
and quantity >= 1
and (book.title = \"\"
or book.title is null
or book.author = \"\"
or book.author is null)
and i.isbn13 >1");
So i'm not that experienced in programming, and am working on some php.
My queries (not counting my broken if-else statements >_>), but when I submit 1 query (query2 for example), that works, it prints the results, as well as the results of another query7. How can I stop that?
Also if anyone has any clue where I failed in my if-else statements for the first query and query6, I'd appreciate some insight (they all use html submit buttons)
Thanks!
Here's my problem php code:
$lastName = $_POST['lastName'];
if ($_Post['lastName'] = "") {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id ";
} Else {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query = $query . "'" . $lastName . "' ORDER BY con_lname;";
$rgroups = $_POST['rgroups'];
if ($_Post['rgroups'] = "") {
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = ";
$query6 = $query6 . "'" . $rgroups . "' Group BY r.rev_groups_id;";}
Else {
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = ";
$query6 = $query6 . "'" . $rgroups . "' ";}
$check = $_POST['check'];
$query7 = "Select c.con_fname, c.con_lname, s.Contact_con_id,
IF(s.Contact_con_id IS NULL, 'NO', 'YES')
From Contact c Left Join (Select Contact_con_id FROM Speakers
WHERE speaker_year = '". $check . "') As s
ON c.con_id = s.Contact_con_id";
$query7 = $query7 . " ORDER BY c.con_fname;";
(this is the code that prints on every result)
$average = $_POST['average'];
$query5 = "SELECT c.con_fname, r.Reviewer_Contact_con_id, question_id, AVG( DISTINCT question_score)
FROM Contact c, Individual_Review r
WHERE r.Reviewer_Contact_con_id = c.con_id
AND con_fname = ";
$query5 = $query5 . "'" . $average . "' GROUP BY r.Proposal_proposal_id;";
(example of working code. you can put in George next to con_fname to get a result)
// 1. Format your code with indents, etc.
// 2. Comment your code
// 3. Don't pass $_POST data straight to your sql.
// 4. Variables are case sensitive, including POST
$lastName = $_POST['lastName'];
if ($lastName = "") {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id ";
}else{
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query = $query . "'" . $lastName . "' ORDER BY con_lname;";
// if you did the first if, then this broke.
// Use:
// echo $query;
// to see what you have so far.
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id
AND con_lname = '".$lastName."' ORDER BY con_lname";
$rgroups = $_POST['rgroups'];
// you can go like $query .=
// you don't have to do $query = $query;
// so all of this could be:
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local' ";
if ($_Post['rgroups'] = "") {
$query6 .= " AND r.rev_groups_id = '" . $rgroups . "' Group BY r.rev_groups_id;";
}else{
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' ";
}
$check = $_POST['check'];
You could add your $query7 in some if condition to avoid that
Note: I am dealing only with your PHP structure. I haven't looked at your SQL syntax at all. But I gave you the tools to see if SQL is returning what you think it should be returning.
<?PHP
// here are some functions for ya
function sqlarr($sql, $numass=MYSQL_BOTH) {
// MYSQL_NUM MYSQL_ASSOC MYSQL_BOTH
$got = array();
$result=mysql_query($sql) or die("$sql: " . mysql_error());
if(mysql_num_rows($result) == 0)
return $got;
mysql_data_seek($result, 0);
while ($row = mysql_fetch_array($result, $numass)) {
array_push($got, $row);
}
return $got;
}
// Sql fetch assoc
function sqlassoc($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
$row = mysql_fetch_assoc($query);
return $row;
}
function sqlrow($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
$row = mysql_fetch_row($query);
return $row;
}
function sqlquery($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
return $row;
}
function printr( array $array, $label = '' ){
echo '<pre>'.$label;
print_r( $array );
echo '</pre>';
}
// This isn't the best, but it's better than nothing
// use PDO when you get more advanced
function makeSomewhatSafe($str){
return htmlspecialchars(stripslashes(strip_tags($str, '<p>')), ENT_QUOTES);
}
// good practice: initiate any variables you use at the beginning
// we're going to go ahead and strip them here too to try to avoid sql injection
$rgroups = makeSomewhatSafe($_POST['rgroups'] );
$lastName = makeSomewhatSafe( $_POST['lastName'] );
$query = NULL;
$speakerContactResulst = array();
$check = makeSomewhatSafe( $_POST['check'] );
$average = makeSomewhatSafe($_POST['average']);
// if($_Post['lastName'] = "") {
// we're going to see if it has a value
// another way to do this if your empty isn't working is to do
// if( strlen( $lastName ) > 0 ){
if( empty( $lastName ) ){
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id ";
}else{
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query .= "'" . $lastName . "' ORDER BY con_lname";
echo 'This query states: '.$query.' <br /><br />';
$speakerContactResulst = sqlarr( $query );
printr( $speakerContactResulst, 'speakerContactResulst ');
if ( ! empty( $rgroups ) ){
$query = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' Group BY r.rev_groups_id;";
}else{
// I dont know if you matters, but keep your else's more compact. Don't do like you had with the else on a new line
// str'; }
// else {
$query = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' ";
}
$groupResults = sqlarr( $query );
printr( $groupResults, 'groupResults' );
$query = "Select c.con_fname, c.con_lname, s.Contact_con_id,
IF(s.Contact_con_id IS NULL, 'NO', 'YES')
From Contact c Left Join (Select Contact_con_id FROM Speakers
WHERE speaker_year = '". $check . "') As s
ON c.con_id = s.Contact_con_id ORDER BY c.con_fname;";
$checkResults = sqlarr( $query );
$query = "SELECT c.con_fname, r.Reviewer_Contact_con_id, question_id, AVG( DISTINCT question_score)
FROM Contact c, Individual_Review r
WHERE r.Reviewer_Contact_con_id = c.con_id
AND con_fname = '" . $average . "' GROUP BY r.Proposal_proposal_id;";
$averageResults = sqlarr( $query );
?>