Print single value from object in php - 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, "

Related

PHP PDO MySQL array only returning column names [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I am having an issue with my prepared SELECT result array not holding the actual column values. I know how to get data from an sql database using Java, however I am having issues with PHP PDO. I am connected to a remote AWS database that I know works. Here is the code:
$conn = new PDO($dsn, $username, $password);
//echo "Test";
Here I want to get all the column's data
$sth = $conn->prepare("SELECT 'id', 'short-des', 'full-des', 'image-urls', 'date-created' FROM projects");
$sth->execute();
I have placed PDO::FETCH_BOTH, PDO::FETCH_ASSOC, PDO::FETCH_COLUMN. The result at the end of this post is a result of me leaving the fetchall() blank. When I insert any of the PDO::styles no values are returned. I have done other scenarios such as using var_dump along with the styles in the fetch statement which provide actual results, BUT no actual values that the columns contain.
$row = $sth->fetchAll();
echo "<br>" . $row[0] . "<br>";
echo "<br>" . $row[1] . "<br>";
$column1 = $row[0];
$column2 = $row[1];
for($i = 0; $i < 5; $i++){
echo " " . $column1[$i];
$var = $column1[$i];
echo " = " . $var . " , ";
}
for($i = 0; $i < 5; $i++){
echo " " . $column2[$i];
$var = $column2[$i];
echo " = " . $var . " , ";
}
This is the resulting text:
64-bitPDO is available
Array
Array
id = id , short-des = short-des , full-des = full-des , image-urls = image-urls , date-created = date-created , id = id , short-des = short-des , full-des = full-des , image-urls = image-urls , date-created = date-created , Connected successfully
I'm guessing its some stupidly simple reason that it is not showing actual values. I am not familiar with the "fetch" concept since I'm coming from JDBC, however I have been spending the past few days trying to get it to work to no avail. I have looked at similar posts such as this post, and this post, and this post. These seem to handle slightly different issues. Unfortunately I want to use a prepared statement instead of an actual query.
I believe the problem is your single-quotes. Try this:
$sth = $conn->prepare("SELECT `id`, `short-des`, `full-des`, `image-urls`, `date-created` FROM projects");
Note: backticks ` are not the same as single-quotes '.

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

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'];
}

Pass PHP Variable into WHERE/AND MySQL Query

I'm trying to pass a value for a query that takes in a variable from an earlier Sql query and then compares the result against a field from another table. But I can't seem to figure out my syntax.
$topName = $row_rsAdminDetails['fullName'] ;
$TESTqueryTwo =
"SELECT * FROM participants, admin WHERE admin.over_id = participants.fk_over_id AND participants.dr_over_names LIKE '%$topName%'";
$TESTresult2 = mysql_query($TESTqueryTwo) or die(mysql_error());
the php output I'm looking to do:
<?php
// Print out the contents of each row
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
echo $row_TESTresultTwo['userName']. " - ". $row_TESTresultTwo['Participant_Name'];
echo "<br />";
}
?>
Problem could be on this line:
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
should be
while($row_TESTresultTwo = mysql_fetch_array($TESTresult2)){
// as you have no $TESTresultTwo variable...
}
And also try with the query ... with LIKE '%".$topName."%'"

PHP multiple entries

I'm creating a small project with PHP/MYSQL but i can't get my query working the way i need it. I have 2 tables
Table 1 (char):
Id, name.
Table 2 (spells):
Id, char, spell_name.
I'm getting the output:
Name Spell1
Name Spell2
Name Spell3
But I need it to be:
Name Spell1
Spell2
Spell3
Here's my query:
$query = "SELECT char.name AS name, spells.spell_name AS spell
FROM char, spells
WHERE (char.id = spells.spell_name)";
Any ideas?
I think you're gonna have to first get the ID of the character to query, and then pull the spells s/he has access to. Example:
$char_id = 0; // value would be assigned arbitrarily.
$query = "SELECT *
FROM 'spells' s
WHERE s.char = $char_id;";
$result = $pdo->query($query);
while($row = $result->fetchObj()){
// do something with the spells obj here
}
With SQL, you need to grab full rows at a time, so I believe the situation you want isn't possible.
As Goldentoa11 wrote. Make two selects, or create query with two result sets (more selects in one command), or accept current state (is normal and you can verify data consistency). I prefer current state, but sometimes use any of described solution (based on query frequency, size of result etc.).
If you need to list such data, you can than use something like this:
$currentName = null;
while ($row = mysql_fetch_object($result))
{
if ($currentName != $row->name)
{
echo "<b>" . $row->name . "</b><br />";
$currentName = $row->name;
}
echo $row->spell_name . "<br />";
}

Sql query only printing first row

I am coding in php and the code takes data from an array to fetch additional data from a mysql db. Because I need data from two different tables, I use nested while loops. But the code below always only prints out (echo "a: " . $data3[2]; or echo "b: " . $data3[2];) one time:
foreach($stuff as $key)
{
$query3 = "SELECT * FROM foobar WHERE id='$key'";
$result3 = MySQL_query($query3, $link_id);
while ($data3 = mysql_fetch_array($result3))
{
$query4 = "SELECT * FROM foobar_img WHERE id='$data3[0]'";
$result4 = MySQL_query($query4, $link_id);
while ($data4 = mysql_fetch_array($result4))
{
$x += 1;
if ($x % 3 == 0)
{
echo "a: " . $data3[2];
}
else
{
echo "b: " . $data3[2];
}
}
}
}
First and foremost, improve your SQL:
SELECT
img.*
FROM
foobar foo
INNER JOIN foobar_img img ON
foo.id = img.id
WHERE
foo.id = $key
You will only have to iterate through one array.
Also, it appears that you're actually only selecting one row, so spitting out one row is expected behavior.
Additionally, please prevent yourself from SQL injection by using mysql_real_escape_string():
$query3 = "SELECT * FROM foobar WHERE id='" .
mysql_real_escape_string($key) . "'";
Update: As Dan as intimated, please run this query in your MySQL console to get the result set back, so you know what you're playing with. When you limit the query to one ID, you're probably only pulling back one row. That being said, I have no idea how many $keys are in $stuff, but if it spins over once, then it will be one.
You may be better off iterating through $stuff and building out an IN clause for your SQL:
$key_array = "";
foreach($stuff as $key)
{
$key_array .= ",'" . mysql_real_escape_string($key) . "'";
}
$key_array = substr($key_array, 1);
...
WHERE foo.id IN ($key_array)
This will give you a result set with your complete list back, instead of sending a bunch of SELECT queries to the DB. Be kind to your DB and please use set-based operations when possible. MySQL will appreciate it.
I will also point out that it appears as if you're using text primary keys. Integer, incremental keys work best as PK's, and I highly suggest you use them!
You should use a JOIN between these two tables. It the correct way to use SQL, and it will work much faster. Doing an extra query inside the loop is bad practice, like putting loop-invariant code inside a loop.

Categories