Display data from several fields in MySQL-table with specific id - php

I have the following code (SQL-query tested in phpMyAdmin and seems to work) that fetch data from selected columns:
$ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : array();
if (is_array($ids)) $ids = implode(',', $ids);
if (!empty($ids)) {
$sql = "SELECT upload, upload2, upload3, upload4, upload5 FROM wp_site_table WHERE cid IN($ids) ORDER BY FIELD(cid, $ids)";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ) { ... } }
The problem I have is that I want to output all fields from selected cid.
This code will only display the first cid result.
echo $result->upload;
Let's say $ids contain cid 1, 4 and 7 I'd like to output upload, upload2, upload4, upload5 from all those specific rows. How? Use an array in some way?
kind regards
Johan

If you want to echo all the fields, just do it:
echo $result->upload . '<br>' . $result->upload2 . '<br>' . $result->upload3 .
'<br>' . $result->upload4 . '<br>' . $result->upload5;
You should perhaps consider redesigning your database so you don't have repeated fields in each row. It would be better to have another table where each upload is in a row of its own, so there's no hard-coded limit on the number of these values. Then you can use a JOIN query to get all the uploads, and they'll be in an array.

With '$wpdb->get_results' output defaults to OBJECT type. Try using pre defined constant : ARRAY_A , it will result the output as an associative array.
$sql = "SELECT upload, upload2, upload3, upload4, upload5 FROM wp_site_table WHERE cid IN($ids) ORDER BY FIELD(cid, $ids)";
$results = $wpdb->get_results($sql, ARRAY_A) or die(mysql_error());
To access, simply use :
foreach( $results as $result ){
echo $result['upload'];
}

Related

Remove Array From Json in PHP

hi i have a backend with php in cpanel and i have a problem with one of jsons . this is part of my php code :
...
}elseif ($work == "dollardate") {
$query3 = "SELECT * FROM tabl_dollar_date";
$result3 = $connect->prepare($query3);
$result3->execute();
$out3 = array();
while ($row3 = $result3->fetch(PDO::FETCH_ASSOC)) {
$record3 = array();
$record3["dollar"] = $row3["dollar"];
$record3["date"] = $row3["date"];
array_push($out3, $record3);
}
echo json_encode($out3);
}
?>
this code show this in json :
[
{
"dollar":"15000",
"date":"1397-12-12"
}
]
how can remove array from json and show the json like this :
{
"dollar":"15000",
"date":"1397-12-12"
}
Easiest way (according his code):
change line
echo json_encode($out3);
to
echo json_encode($out3[0]);
One solution is that if you just want the latest value (in case there are multiple records in the table), then change the SELECT to order by date descending also set LIMIT to 1 to only get the 1 record anyway, and remove the loop to fetch the data and just fetch the 1 record...
$query3 = "SELECT `date`, `dollar`
FROM `tabl_dollar_date`
ORDER BY `date` desc
LIMIT 1";
$result3 = $connect->prepare($query3);
$result3->execute();
$row3 = $result3->fetch(PDO::FETCH_ASSOC);
echo json_encode($row3);
As you know which fields you want from the SELECT, it's good to just fetch those fields rather than always using *. This also means that as the result set only contains the fields your after, you can directly json_encode() the result set rather than extracting the fields from one array to another.

PHP - Count how many results are displayed in foreach

With the foreach loop, I wanna count how many results are displayed. For example, if it's displaying
Jack Ane
Steve Jobs
Sara Bill
I want to echo that there are 3 results.
Likewise, if it's like
Marc Kil
Bill Smith
I want to echo that there are 2 results.
It's a bit tricky for me becasue this is my code:
<div>
<?php
$container = array();
if (is_array($row))
{
foreach ($row as $data) {
if(!isset($container[$data->first_name . $data->last_name])) {
$container[$data->first_name . $data->last_name] = $data;
echo $data->first_name . " " .$data->last_name . "</div>";
}
}
}
?>
</p>
</div>
How exactly would I be able to do that? Since these values are coming straight from the database, I was thinking of doing a database count but there are duplicate values in the database since I'm logging the views of users with the first and the last name. So when I try to do it, say for example there are 20 Jack Ane in my database. Then it shows me all of the 20 Jack Ane's instead of just one because I just want it once.
Sorry if it's confusing.
Thanks.
I traditional use the count() to do that if you dont use any :
foreach ($row as $data) {
if(!isset($container[$data->first_name . $data->last_name])) {
$container[$data->first_name . $data->last_name] = $data;
echo $data->first_name . " " .$data->last_name . "</div>";
}
}
echo "Results: " . count($row);
Hope that help you.
I suggest you to rewrite your query. If you will do this in right way, you will get faster solution, with no needs to new array and unnecessary "isset" checks.
The reason you get duplicated data from query may be:
1 - Wrong query logic
2 - Query is OK, but you need to use DISTINCT or GROUP BY to remove duplicates
If you use PDO, you can then get number of returned rows just by using rowCount() method
$sql="SELECT * from table WHERE blablabla";
$result = $this->db->query($sql);
$result->rowCount(); // here
Then you can fetch $result->fetchAll(); and print data.
You can to do a SELECT DISTINCT or a GROUP BY across the two columns to have the database do the work and eliminate the duplicate checking in your PHP. To do this you can use something like the following:
SELECT DISTINCT first_name, last_name FROM users;
SELECT first_name, last_name FROM users GROUP BY first_name, last_name;
DISTINCT is more succinct while GROUP BY supports more flexibility.
In your example, since you are building an associative array, you can just do a count() after the loop, but you will have cleaner code if you have the database do it:
$count = count($container);
You could do an easy variable that increments inside your foreach that gives you the exact count, then use the variable to create actions depending on it's value. Because if you count the container and you wish to filter out the results inside the container, you won't get the filtered amount.
<?php
$container = array();
if (is_array($row))
{
$count = 0;
foreach ($row as $data) {
if(!isset($container[$data->first_name . $data->last_name])) {
$container[$data->first_name . $data->last_name] = $data;
echo $data->first_name . " " .$data->last_name . "</div>";
$count++;
}
}
}
if ($count > 0) {
echo "There were $count results.";
}
?>
use:
echo "Results: " . count($container);

Print single value from object in php

I have MYSQL table for the setting in my script , and i fetch this table in php object , i know how to print the full object by using while() , but i want to print a single value by using key .
This is MYSQL table :
setting_name setting_value
site_name Blue Box
site_email abdullah#gmail.com
template_dir defualt
language_dir english
date_format d.m.y
time_format h:m
site_logo logo.png
and this is how i'm fetching the table in object :
$query_set = "SELECT * FROM setting";
$result_set = mysql_query($query_set)
or die ("Error in query: $query_set. " . mysql_error());
$row_set = mysql_fetch_object($result_set);
i can print whole table by this code:
while($row_set = mysql_fetch_object($result_set))
{
echo "<br />";
echo $row_set->setting_name;
echo " ";
echo $row_set->setting_value;
echo "<br />";
}
but i need to print single value from the table by using key .
note : i know that i can filter from my query , but i want to select all my table to print group of values in different locations in the same page .
If you need just one value, then you could change your SQL query. Something like,
$query_set = "SELECT * FROM setting WHERE setting_name='site_name'";
If you have to use more than one values, you can try this
$data = array();
while ($result = mysql_fetch_assoc($resource)) {
$data[$result["setting_name"]] = $result["setting_value"];
}
//Now you will be able to use it like this.
echo $data["site_name"];
Doing it with objects,
$data = stdClass();
while ($result = mysql_fetch_object($resource)) {
$data->$result->setting_name = $result->setting_value;
}
// For using it.
echo $data->site_name;
You need this query, but googling is so hard nowadays. Don't forget to filter your input etc.
SELECT s.setting_name, s.setting_value
FROM settings s
WHERE s.setting_name IN ('my_key', 'my_other_setting', 'some_other_setting')
If you want only the value, remove "s.setting_name, "

How to access an Arrays value by the value of another array

$query = "select Code , count(ListID) as nums from accesstable where Cust=" . $_SESSION ['Cust'] . " and App=" . $_SESSION ['App'] . " group by Code";
$result = mysql_query ( $query );
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[] = $row['nums'];
}
This is the structure of my code that I am trying to learn how to properly access... Here is my dilemma... I am trying to figure out how to explicitly find the associated count of nums dependent on the value of a Code.
Let me explain in better detail where my issue is....
Lets say the list of codes is
Code nums
1 624
7 825
571 450
9 393
2 739
9 590
The above code does successfully allow me to separate those values strictly into keys and values but I cannot figure out how to grab the nums value if the code is = to a certain value... I have currently been trying to declare a variable above the entire snippet of code and then declare it within the while statement but cannot figure out how to get the value to bind properly.... I will repaste the above code with one of my many failures in the while statement to give a better idea.
$Answer1 = 0;
$query = "select Code , count(ListID) as nums from accesstable where Cust=" . $_SESSION ['Cust'] . " and App=" . $_SESSION ['App'] . " group by Code";
$result = mysql_query ( $query );
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[] = $row['nums'];
($Codes == 1){
$Answer1 = // Right Here I want to Get the value 624 related to Code 1... Dont want to embarass myself with examples of what I have tried...
}
So how do I make a condition to output the value associated with a Code? I want to explicitly define these values as the list of codes can change with each customer... Luckily there are only a certain amount of codes so its not like I need to define too many of them... I just want to make sure I can get the nums value associated with a code and display it.
Hope I did a good job explaining this. :)
I'd do:
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[$row['Code']] = $row['nums'];
}
and, to access the value associated to a code:
$code = 1;
$value = $values[$code];
Since they would share the same array key, something like this would work-
if ($Codes[$key] == 1){
$Answer1 = $Values[$key];
}

PHP, MySQL: Making a better search?

I've made a search box feature that allows me to type in a word and then it finds any matches of the word in my database. However, it only finds EXACT matches. I'm looking for suggestions on how to make the search better.
The code below is what i currently use for searching the databases for users that might be matches for the user searching.
$search_keys = array('fname', 'lname', 'email' );
foreach ( $search_keys as $key )
{
$result = mysql_query( "SELECT id FROM users WHERE " . $key . " LIKE " . "\"{$str}\"" ) or die(mysql_error());
while ( $row = mysql_fetch_array( $result ) )
{
// Get the User
$tmp_user = new User();
$tmp_user->getUserById( $row['id'] );
// Add User to list of potential candidates
array_push($users, $tmp_user);
}
}
I see two points where you can improve your code fragment. But first of all take care that $str is properly formatted to be safely used in your SQL query. Otherwise you will run into a problem called SQL Injection. I assume that now for your code.
Use wildcards with the LIKE SQL function.
Search across the three fields with one SQL query.
Please see the example code which contains both suggestions. First the SQL query is build. There is only need to run one query for all (three) fields instead of one query per field. That's useful if you extend your search later.
/* build SQL query */
$conditions = array();
$search_keys = array('fname', 'lname', 'email' );
foreach ( $search_keys as $key )
{
$conditions[] = "{$key} LIKE \"%{$str}%\""; # Wildcard (%); [] works like array_push()
}
$query = sprintf('SELECT id FROM users WHERE (%s)', implode(' OR ', $conditions));
/* run SQL query */
$result = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_array( $result ) )
{
// Get the User
$tmp_user = new User();
$tmp_user->getUserById( $row['id'] );
// Add User to list of potential candidates
array_push($users, $tmp_user);
}
Well there is always the simplest method of adding the wildcard operator, so if they enter 'Jam' it would be
SELECT id FROM users WHERE fname LIKE '%Jam%'
etc...
EDIT: The point being it would return a match on JAMIE or JAMES or LogJam or (you get the idea), which means they don't need to remember the whole name, just some part of it.
I would suggest to use a fulltext database as solr or sphinx for this kind of behaviour.
If you can't or don't want to install it, you should add % to your code.
$result = mysql_query( "SELECT id FROM users WHERE " . $key . " LIKE " . "\"%{$str}%\"" ) or die(mysql_error());
you should try
$result = mysql_query( "SELECT id FROM users WHERE " . $key . " LIKE " . "%" . $str . "%" ) or die(mysql_error());

Categories