How can I create a PHP function that will gather all database values and then then return each output as a variable. I have the code to SELECT one value from the database and display it as a variable in PHP. Here is the code:
function GetWebsiteName() {
$sql = "SELECT value FROM configuration WHERE name = 'website_name'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo $row['value'];
}
$GetWebsiteName = "GetWebsiteName";
Basically I wanted to expand it so that instead of SELECT only one value in this case VALUE I want to SELECT * all values from the database and output them one by one. The issue that I am having is that when calling my return data I am not sure how to code it. I have an example of the SELECT. Here is the code:
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(150) NOT NULL,
`value` varchar(150) NOT NULL,
PRIMARY KEY (`id`)
function GetConfigurationData() {
$sql = "SELECT value FROM configuration";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo $row['website_name'];
echo $row['website_url'];
echo $row['website_email'];
}
Does anybody know how to select each one and then output the value using PHP?
function getConfigurationData($name) {
$sql = "SELECT `$name` FROM `configuration`";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
return $row[$name];
}
Usage:
echo getConfigurationData('website_name');
Using something like PDO would be better, though.
Related
Description: I'm creating the database name automatically consisting of main table name and appending the full name relative to what is selected in dropdown menus.
Code:
if ($leagueSelect === $result['leagueName'] && $divisionSelect === $result['divisionID'] && $tourType === 'robin') {
$tableName = "footleague_".$leagueSelect.$divisionSelect;
/****CREATE TABLE****/
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query = "CREATE TABLE IF NOT EXISTS `".( $tableName )."` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`round` TEXT NULL,
`logoHome` TEXT NULL,
`home` TEXT NULL,
`usrHome` TEXT NULL,
`scoreHome` INT(11) NULL,
`scoreAway` INT(11) NULL,
`logoAway` TEXT NULL,
`away` TEXT NULL,
`usrAway` TEXT NULL,
`confirm` INT(11),
PRIMARY KEY (`id`)
)";
$db->setQuery($query);
$result = $db->execute();
if ($result == true) {
echo 'Table created successfully!';
}else{
echo "Something went wrong with table creation. Please try again.";
}
}
This works perfectly and it creates a new table and all of the columns.
The problem comes when storing data into this table. I need to be able to take the table name which is stored in a variable and store the data into it. Same as in CREATE TABLE.
I tried it like this:
$query = "INSERT INTO ".$tableName." (round, logoHome, home, usrHome, logoAway, away, usrAway),
VALUES ('".$round."' , '".$logoHome."' , '".$home."' , '".$usrHome."' , '".$logoAway."' , '".$away."' , '".$usrAway."')";
$db->setQuery($query);
$result = $db->execute();
...but it doesn't give me any errors and it doesn't store the data.
I tried also with stdClass object but I don't know how to get the table name in there:
$data = new stdClass();
$data->round = $round;
$data->home = $home;
$data->usrHome = $usrHome;
$data->logoHome = $logoHome;
$data->away = $away;
$data->usrAway = $usrAway;
$data->logoAway = $logoAway;
$db = JFactory::getDBO();
$db->insertObject($tableName, $data);
How can I get this to work?
Thank you.
I solved it like this:
$data = new stdClass();
$data->round = $round;
$data->home = $home;
$data->usrHome = $usrHome;
$data->logoHome = $logoHome;
$data->away = $away;
$data->usrAway = $usrAway;
$data->logoAway = $logoAway;
$db = JFactory::getDBO();
$db->insertObject($tableName, $data);
if ($result == true) {
echo 'Tournament was created successfully!';
}else{
echo 'ERROR!';
}
I have two table in MySql, one for users information and another for new posts that post by users:
new_post table:
id int(11)
title varchar(100)
content text
created_at datetime
url_image varchar(300)
user_id varchar(23)
users table:
uid int(11)
unique_id varchar(23)
name varchar(50)
user_profile_image varchar(300)
email varchar(100)
encrypted_password varchar(80)
salt varchar(10)
created_at datatime
By using PHP I wanna create Json array. In Json array I want to return new_post entry and also user_profile_image that store in users table and I can access to it by user_id and unique_id.
I created PHP file and work fine for return new_post entry but I don't know how get user_profile_image and return with them.
It's my PHP code:
<?php
//Create Database connection
error_reporting(E_ALL ^ E_DEPRECATED);
include 'conf.php';
$pageNumber = $_GET['page_number'];
$sql="select * from new_post order by ID DESC limit ".getpage($pageNumber);
$result= mysql_query($sql);
function getpage($p){
$p--;
return ($p*10).",10";
}
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['content'] = ($row['content']);
$row_array['created_at'] = $row['created_at'];
$row_array['url_image'] = $row['url_image'];
//push the values in the array
array_push($json_response,$row_array);
}
array_walk_recursive($json_response, function(&$val) {
$val = utf8_encode($val);
});
echo json_encode($json_response, JSON_UNESCAPED_SLASHES);
print "ok";
?>
Any idea how to do it?
You can join the two tables in your query like:
$sql="select * from new_post left join users on new_post.user_id = users.unique_id order by ID DESC limit ".getpage($pageNumber);
Now, you can use $row_array['user_profile_image']
I'm new to both PHP & mySQL, but I suspect some apostrophe related bug here (maybe).
For some reason the first query always seems to return null because the
echo "result: $result\n";
never prints any data. At the first call that is expected, but at the second call the player has been added to the db. My database works in the sense that I can see that rows with correct ids are added to the database (via phpMyAdmin).
Can you help me spot the error?
<?php
require_once('Db.php');
$db = new Db();
// Quote and escape form submitted values
$id = $db->quote($_POST['id']);
$score = $db->quote($_POST['score']);
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = `$id`");
echo "result: $result\n"; // Never prints any data
if($result->num_rows == 0) {
// Row not found. Create it!
$result = $db->query("INSERT INTO `xxxxxx`.`Player` (`id`,`score`) VALUES (" . $id . "," . 0 . ")");
}
?>
First, drop those backticks from id in WHERE clause, otherwise it will take the field name from id column instead of 'id'.
Then you need to fetch data from $result:
$result = $db->query("SELECT id FROM `xxxxxx`.`Player` WHERE id = '$id'");
$row = $result->fetch_array();
echo $row['id'];
Or if there are more rows than one:
while($row = $result->fetch_array())
{
echo $row['id'];
}
You are using backticks in your query for $id. Remove them and try again.
Your query should be
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = $id");
OR
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = ".$id."");
I have a database that is designed for Football players and so have the table with the following fields:
Person_ID
First_Name
Surname
NicName
Address_Line_1
Contact_Number
Date_of_birth
Postcode
I need to extract the Person_ID for a player without actually entering the ID number as players will not know their individual number and is designed to be used just by the system.
I have the My sql code for selecting a player when certain values are entered:
SELECT `Person_ID` FROM `person` WHERE `First_Name` = 'A Name' and `Surname` = 'Another Name'
This does not however return very well within php when placed into a function. The function I currently have is shown below (php)
function showid($fname, $sname, $d) {
$sql = "SELECT `Person_ID` FROM `person` WHERE `First_Name` = '$fname' and `Surname` = '$sname'";
$result = mysqli_query($d, $sql);
if (!$result)
print ("$sql failed".mysqli_error($d));
else {
print ("$fname $sname is selected<br>");
}
}
$name and $sname are values which will be entered by the user and they will then be able to transfer to a different team or update their account etc but I need to have the ID selected so that further functions and queries can work fully.
If you want to fetch the ID of the selected player, use the fetch_array function
http://php.net/manual/en/mysqli-result.fetch-array.php
function showid($fname, $sname, $d) {
$sql = "SELECT `Person_ID` FROM `person` WHERE `First_Name` = '$fname' and `Surname` = '$sname'";
$result = mysqli_query($d, $sql);
if (!$result)
print ("$sql failed".mysqli_error($d));
else {
print ("$fname $sname is selected<br>");
}
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "Your ID is" . $row['Person_ID'];
}
This of course assumes there is only one result (otherwise we would have to loop) so you might want to check $result->num_rows is equal to 1 and return an error if it isnt (assuming you arent using UNIQUE in your database)
now i use this code:
$welcome_text = mysql_query("SELECT * FROM `text` WHERE `name` = 'welcome'");
while ($row = mysql_fetch_array($welcome_text, MYSQL_ASSOC)) {
echo $row['content'];
}
Is it possible to use it without WHILE if i know exactly which one column i need?
Something like this:
$welcome_text = mysql_query("SELECT 'content' FROM `text` WHERE `name` = 'welcome'");
echo $welcome_text;
Thanks
mysql_query makes the query, returns a result set.
mysql_fetch_array fetches the first row from the result set.
$welcome_text = mysql_query("SELECT * FROM `text` WHERE `name` = 'welcome'");
$row = mysql_fetch_array($welcome_text, MYSQL_ASSOC);
echo $row['content'];
Of course, you can shorten your code if you want, but this may make your code more difficult to debug and maintain.
Verbose, clear code > one-liner 'show-off' code.
Including 'just-in-case' checking:
$welcome_text = mysql_query("SELECT * FROM `text` WHERE `name` = 'welcome'");
if($row = mysql_fetch_array($welcome_text, MYSQL_ASSOC)){
echo $row['content'];
}
Good practice to make doubly sure you have what you need before printing it.
Finally, please make sure you sanitize user-submitted data before it goes into your database. If you're not going to use prepared statements, at least use mysql_real_escape_string.
Practice safe SQL, wear a prepared statement to prevent SQL Injections.
I would write a function for this:
// Returns content of first column in first result and
// returns null if query returns no records
function mysql_get_result($sql) {
$query = mysql_query($sql); // you may add error handling ...
if (mysql_num_rows($query) != 0) {
$row = mysql_fetch_array($query, MYSQL_NUM));
return $row[0];
} else {
return null;
}
}
And now you can use:
$welcome_text = mysql_get_result("SELECT `content` FROM `text` WHERE `name` = 'welcome'");
Note: You may throw an exception instead of returning the null value. But what is better is hard to say and it may depend on your programming style.
That's not entirely the same thing. In your first sample, you're iterating over multiple rows, not columns.
Unless you're certain that there's only one row with the name welcome, you're still going to need the loop.
You are right that you shouldn't select * when you only need some of the columns, it's wasteful.
In other words, you should use the only slightly modified:
$welcome_text = mysql_query("SELECT `content` FROM `text` WHERE `name` = 'welcome'");
while ($row = mysql_fetch_array($welcome_text, MYSQL_ASSOC)) {
echo $row['content'];
}
$welcome_text = mysql_fetch_row(mysql_query("SELECT 'content' FROM `text` WHERE `name` = 'welcome'"));
echo $welcome_text[0];