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
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.
Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}
I am looking for a way to get the sum of a column. The query i am using looks like this:
public function gradeRound($rating)
{
$sql = mysql_query("Select SUM(rating) AS grades FROM" . $this->_prefix . "media_set_rating WHERE set_id = set_id");
mysql_real_escape_string($rating->rating);
$row = mysql_fetch_assoc($sql);
$grades = $row['grades'];
}
I am not sure how to get this properly formatted for the controller. right now my controller has this.
i put a text box on the page and echoed $grades - this is also included in the view as so:
$this->_view->assign('grades', $grades);
so that i can use it.
I tried replacing $setId with $rating both of which are being requested at the top.
I do not get anything out of my echo. I had -1 in there earlier. i am not sure where it was getting that from. I was trying different methods and got different results.
appreciate any hints or clues as to how to do this.
thanks
Revised 2:17 EST May 27 2013
Thanks Niko. I must be getting tired!
Here is the revised query:
public function gradeRound($rating)
{
$sql = sprintf("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating
WHERE set_id = set_id");
$sum = mysql_query($sql);
$row = mysql_fetch_assoc($sum);
$grades = $row['grades'];
return $grades;
}
$grades = $setDao->gradeRound($setId);
Your SQL query looks rather odd. Depending on the type of "set_id", it is supposed to look like this:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = '". mysql_real_escape_string($rating->rating) ."'"
);
for ยด$rating->rating` being a string. For an integer, it should be:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = ". (int) $rating->rating
);
And in total (adding also a return statement):
public function gradeRound($rating)
{
// expecting "set_id" to be an integer field
$result = mysql_query("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating WHERE set_id = ". (int) $rating->rating);
$row = mysql_fetch_assoc($result);
return $row['grades'];
}
Hope this will help You !
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
if i have 4 variables and i want to select DISTINCT values form data base
<?php
$var1 = ""; //this variable can be blank
$var2 = ""; //this variable can be blank
$var3 = ""; //this variable can be blank
$var4 = ""; //this variable can be blank
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE **keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4'** ");
?>
note: some or all variables ($var1,$var2,$var3,$var4) can be empty
what i want:
i want to neglect empty fields
lets say that $var1 (keywords) is empty it will select all empty fileds, but i want if $var1 is empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");
if $var2 is empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR date='$var3' OR forums='$var4' ");
if $var1 and $var2 are empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE date='$var3' OR forums='$var4' ");
and so on
Try this.
$vars = array(
'keywords' => '', // instead of var1
'author' => '', // instead of var2
'date' => '', // instead of var3
'forums' => '', // instead of var4
);
$where = array();
foreach ($vars as $varname => $varvalue) {
if (trim($varvalue) != '') $where[] = "`$varname` = '" . mysql_real_escape_string($varvalue) . "'";
}
$result = mysql_query("SELECT DISTINCT title, description FROM table WHERE " . join(" OR ", $where));
Thanks alot every one specially experimentX .. Your answer helped me to get the right function i Just replaced (isset) with (!empty) .. Then every thing will be more than OK
$vars = array(
(!empty($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(!empty($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(!empty($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(!empty($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" OR ", $newvars);
$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
with this function if there is empty variable it will be neglected
Thanks again every one for your helpful suggestion
make your select statement string before you call mysql_query(...) so do something along the lines of this:
$queryString = "Select DISTINCT title, description FROM table WHERE";
if(!empty($var1))
$queryString .= " keywords = $var1";
and so forth for all of your variables. you could also implement a for loop and loop through your $var1 - $var# and check for !empty($var#)
Why do you not simply build a if else structure?
Like
if ($var1!="" && $var2!="" && $var3!="" && $var4!=""){
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4' ")
} else if ($var2!="" && $var3!="" && $var4!=""){
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");
} else if {
...
}
(I just posted the below in his duplicate post, so I'm re-posting the below here)
Forgive me if anything is wrong, it's very late here and I just typed this in notepad on Windows, without an environment to test on. * Use with caution * :)
$vars = array(
'blah1' => '',
'blah2' => '',
'blah3' => '',
);
$sql_statement = "SELECT first, last FROM names WHERE";
$clause = "";
foreach($vars as $k=$v)
{
$k = trim($k);
if(!empty($k))
{
$clause .= " `$k` = '$v' OR";
}
}
$clause = rtrim($clause, "OR");
// $clause should have what you want.
Well, there are manu ways of doing this but the shortest way I have found is creating an array of the following form
$vars = array(
(isset($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(isset($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(isset($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(isset($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" OR ", $newvars);
$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
Your result for http://localhost/?var1=sadfsadf&var2=sadfasdf&var3=asdfasdf
SELECT DISTINCT title, description FROM table WHERE keyword =
'sadfsadf' OR author = 'sadfasdf' OR date = 'asdfasdf'
Your result for http://localhost/?
SELECT DISTINCT title, description FROM table