I am still trying to learn PHP and have some issues with this code. I have a field $youtubeurl in ID_Vehicles and I am trying to output some code if that field has data in it how do I select that field with this join to output the value like the sample below?
function getDealerSettings($vid)
{
include('db.php');
$query = "SELECT banner, ebay_htmlcss FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";
$result = #mysql_query($query);
if ($result)
{
$row = mysql_fetch_assoc($result);
return array("banner" => trim($row['banner']), "css" => str_replace(array("\n", "\t"), " ",$row['ebay_htmlcss']));
}
return "";
}
function getTemplate($vid)
{
$code = "";
extract($this->getDealerSettings($vid));
if (!empty($youtubeurl))
$code .= "$youtubeurl";
Seems like you just need to add that field to your select statement:
$query = "SELECT banner, ebay_htmlcss, youtubeurl FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";
You need to add youtubeurl to the SELECT statement as well as ensuring it's in your return array, then it should work.
I wasn't returning the value in the array return array("banner" => trim($row['banner']),"youtubeurl" => trim($row['youtubeurl']),
Not necessarily an answer, supplements my comment to the question, I couldn't find a $youtubeurl mentioned before the empty check. If the db does not return anything or the query fails, the needed error handling is also not present. I have added simple error handling to the script. the return array contains ($return_array[0]) $errflag, which can be read to see if there was an error, $errmsg is an array containing the error msg, the third element contains your return array.
function getDealerSettings($vid)
{
$errflag=false;
$errmsg=array();
$return=array();
include('db.php');
$query = "SELECT banner, ebay_htmlcss FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";
$result = #mysql_query($query);
if (!$result){
$errflag=true;
$errmsg[]="Error with db connection". mysql_error();
}else{
$row = mysql_fetch_assoc($result);
$return = array("banner" => trim($row['banner']), "css" => str_replace(array("\n", "\t"), " ",$row['ebay_htmlcss']));
}
$return_array=array($errflag, $errmsg, $return);
return $return_array;
}
Related
I'm trying to make a online user list output all my usernames in a row like this (username, username, username)
The code I'm trying:
$result2 = $db->query("SELECT * FROM `online`");
$fetched2 = $result2->fetch_assoc();
$user_id = $fetched2['user_id'];
$result = $db->query("SELECT * FROM `users` WHERE id = $user_id");
while ($fetched = $result->fetch_assoc())
{
$users_arr[] = array("username"=> $fetched['username']);
}
But it's only returning 1 username from online table and not all in a row, how can i do this?
return json_encode(array("status" => 200, "message" => $users_arr)));
This only outputted 1 username, and also it's outputted in json format which i do not want, i want it outputted like so: User, User, User and not like [{'username': 'vanilla'}]"
Can someone please show me the correct way of using an array or a solution to my problem, thanks!
UPDATE:
Tried this and it worked, but now the dilemma is how do i make the outputted json array to look like User, User instead of ['user1', 'user2']
$users = array();
$result = $db->query('SELECT user_id, ident, u.group_id FROM '.$db->prefix.'online LEFT JOIN '.$db->prefix.'users AS u ON (ident=u.username) WHERE idle=0 ORDER BY ident', true) or error('Unable to fetch online list', __FILE__, __LINE__, $db->error());
while ($user_online = $result->fetch_assoc())
{
$users[] = $user_online["ident"];
}
I tried to use:
$trimmed = trim($users, '[]');
But this threw a warning/error:
PHP Warning: trim() expects parameter 1 to be string
Also tried:
$string = implode('[]', $users);
It does output 2 users, but its formated/outputted like:
user1[]user2
(Moved solution to answer space on behalf of the question author to move it from the question).
Fixed by using:
$string = implode(", ", $users);
I wrote a function to start a tournament and people got Emails twice instead of once. So I tried to debug stuff. As you can see, I fill an array (part[]) with information from my database, shuffle it for the random enemy thing and then want to email the participants their opponents. I cut the whole email thing and just printed the array. But it gets printed twice. What makes me really sick is, that one of the prints appears above the
echo "<hr>";
which is crazy because there is no output.
function start_pre($t_id) {
global $con;
$participants=array();
$sql = "SELECT u.name, u.btag, u.email FROM participant p, user u WHERE p.tournament_id = ".$t_id." AND p.user_id = u.user_id";
$result = mysqli_query($con, $sql);
if ($result) {
while ($row = mysqli_fetch_array($result)) {
$part[] = array(
"name" => $row['name'],
"btag" => $row['btag'],
"email" => $row['email']
);
}
} else {echo "Problem.";}
shuffle($part);
echo "<hr>";
$paare = array_chunk($part, 2);
foreach ($paare as $paar) {
print_r($paar);
}
$sql = "UPDATE tournament SET enrollable='0' WHERE tournament_id='".$t_id."'";
$result = mysqli_query($con, $sql);
}
I cannot include a screenshot of the actual output because of privacy and stuff but I bet you can imagine how a printed array above and below a horizontal line look. Any help is appreciated!
You must be calling the whole function twice. Also, It would perform better if you just use order by rand() in mysql rather than shuffle.
I have a PHP code which has the following output:
[{"stockdata":29655.88482666}]
And I need to change the code on my php to get the result in this format:
[{"data": [29655.88482666]}]
This is the code of my php:
<?php
function getArraySQL(){
$startd = "29964";
$endd = "29968";
$dsn = "prueba";
$connect = odbc_connect( $dsn, '', '' );
$query = "
Select SUM(TON_DESCARGADO) as stockdata
from
(Select unit,[load],enum_LOAD.[name],SUM(dumptons) as TON_DESCARGADO
from hist_dumps inner join hist_loclist on hist_dumps.shiftindex = hist_loclist.shiftindex
and hist_dumps.loc = hist_loclist.locid
inner join enum_LOAD on hist_dumps.[load] = enum_LOAD.[num]
where hist_dumps.shiftindex between '$startd' and '$endd'
GROUP BY loc,UNIT,unit#,[load],enum_LOAD.[name])TEMP1
where unit = 'Stockpile'
GROUP BY unit
order BY UNIT";
if(!$rs = odbc_exec($connect, $query)) die();
$rawdata = array();
$i=0;
while($row = odbc_fetch_array($rs))
{
$rawdata[$i] = $row;
$i++;
}
odbc_close( $connect );
return $rawdata;
};
$stockdata = getArraySQL();
echo json_encode(($stockdata), JSON_NUMERIC_CHECK);
What need to be changed to get the correct format? Should I do something to improve the code of my php?
How should I write it if I connect php to SQL server via PDO and get the same result? (just an optional doubt)
I don't find custom output in json_encode, so if you want to customize the output of array , you would need to prepare it.
I assumed the data exists at zero index (0).
So, I use $stockdata[0]
for JSON_NUMERIC_CHECK replace, used (float)
here is the preparation of output to send exactly you want.
$stockdata = getArraySQL();
$Numeric_data = (float) $stockdata[0];
$data = '[{"data": ['.$Numeric_data.']}]';
echo $data;
Demo
I'm trying to write a script that gets data from a sql server based on the id of the entry in my data base. when I try to access the page using the link with the id of the entry it returns as if it does not recognize the id. Below is the php code :
<?php
require('includes/config.inc.php');
require_once(MYSQL);
$aid = FALSE;
if (isset($_GET['aid']) && filter_var($_GET['aid'], FILTER_VALIDATE_INT, array('min_range' => 1)) ) {
$aid = $_GET['aid'];
$q = "SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft USING(aircraft_id) WHERE aircraft_id = $aid";
$r = mysqli_query($dbc, $q);
if (!(mysqli_num_rows($r) > 0)) {
$aid = FALSE;
}
}// end isset tid
if ($aid) {
while ($acdata = mysqli_fetch_array($r, MYSQLI_ASSOC)){
echo'<h2>'. $acdata['tail_number'] .'</h2>';
}
} else {
echo '<p>This pages was accessed in error.</p>';
}
?>
Any hints?
Try to var_dump($q); before $r = mysqli_query($dbc, $q); to inspect your query and then just execute it through phphmyadmin or in MySQL server terminal directly and see what does it return.
Update:
Use var_dump($q);die(); to stop script from executing after dumping.
You are using a field alias in your query, so you must use that in your echo to:
echo'<h2>'. $acdata['tn'] .'</h2>';
Get rid of the USING(aircraft_id), it causes an error and your query doesn't execute.
"SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft WHERE aircraft_id = $aid"
I guess it's a leftover from a previous version of the query? Using (id) is a shortcut for
FROM
foo
INNER JOIN bar ON foo.id = bar.id
It can be used when the tables to be joined are joined on columns which have the same name. Just shorter to write.
Since you are not joining you have to remove it.
When I run the following MySQL query via PHP and all of the elements of $_GET() are empty strings, all the records in the volunteers table are returned (for obvious reasons).
$first = $_GET['FirstName'];
$last = $_GET['LastName'];
$middle = $_GET['MI'];
$query = "SELECT * FROM volunteers WHERE 0=0";
if ($first){
$query .= " AND first like '$first%'";
}
if ($middle){
$query .= " AND mi like '$middle%'";
}
if ($last){
$query .= " AND last like '$last%'";
}
$result = mysql_query($query);
What is the most elegant way of allowing empty parameters to be sent to this script with the result being that an empty $result is returned?
my solution:
$input = Array(
'FirstName' => 'first',
'LastName' => 'last',
'MI' => 'mi'
);
$where = Array();
foreach($input as $key => $column) {
$value = trim(mysql_escape_string($_GET[$key]));
if($value) $where[] = "`$column` like '$value%'";
}
if(count($where)) {
$query = "SELECT * FROM volunteers WHERE ".join(" AND ", $where);
$result = mysql_query($query);
}
There's no point in running a (potentially) expensive query if there's nothing for that query to do. So instead of trying to come up with an alternate query to prevent no-terms being searched, just don't run the search at all if there's no terms:
$where = '';
... add clauses ...
if ($where !== '') {
$sql = "SELECT ... WHERE $where";
... do query ...
} else {
die("You didn't enter any search terms");
}
With your current code, if everything is empty, you will get the WHERE 0=0 SQL which is TRUE for all rows in the table.
All you have to do is remove the if statements...