Create variable from MySQL datatable that can be used in HTML code - html

So I have a MySQL database and would like to create variables from that database that I can use in HTML code.
For example if I use <video blablabla some stuff src="phpVariable" /video>
I don't want to have a static URL in the HTML code. It should be assigned to a variable based on an SQL query. What is the best way to do this?

First, you need to retrieve the data from the database that you wish to use, using a database query. From there, you can loop through all the results and output them.
Replace 'tablename' with the name of the database table and 'columnName' with the column name.
$con should be used to connect to your database. See https://www.php.net/manual/en/pdo.connections.php
$stmt = $con->prepare("SELECT * FROM tablename");
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['columnName'];
}
If you only needed to retrieve one record, change the code to:
$stmt = $con->prepare("SELECT * FROM tablename");
$stmt->execute();
$row = $stmt->fetch();
echo $row['columnName'];
You can also store the retrieved data as a variable, like this:
$variableName = $row['columnName'];
// Then to use the variable in your code:
echo'<video src='.$variableName.'</video>';
This is very basic PHP though. Have you looked at some online guides?

Related

Admin panel - Creating an edit users button

I've created an admin panel on my website so when the admin logs in he can edit users. I'm trying to get it to create a table that displays a list of all the users on the database, however, when I run it I get the error:
No database selected
Here is the code in my editusers.php:
<?php
include 'adminpage.php';
include 'connection.php';
$sql = "SELECT * FROM Users";
$result = mysql_query($sql)or die(mysql_error());
echo "<table>";
echo "<tr><th>UserID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>D-O-B</th></tr>Username</th><th>Password</th><th>";
while($row = mysql_fetch_array($result)){
$userid = $row['UserID'];
$firstname = $row['FirstName'];
$lastname = $row['LastName'];
$email = $row['Email'];
$dob = $row['DateofBirth'];
$username = $row['Username'];
$password = $row['Password'];
// Now for each looped row
echo "<tr><td style='width: 200px;'>".$userid."</td><td style='width: 200px;'>".$firstname."</td><td>".$scale."</td><td>".$lastname."</td><td>".$email."</td></tr>".$dob."</td></tr>".$username."</td></tr>".$password."</td></tr>";
} // End our while loop
echo "</table>"
?>
First of all it looks like you are using mysql which isn't a wise move. This is because Mysql is actually deprecated and was improved to mysqli. Your problem may be to do with your database connection. You also haven't set a database. Like I said you can set an active database in your connection script. It should or could look something like this.
<?php
$conn = mysqli_connect("localhost", "root", "password", "database");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
After that, your sql query is correct by selecting all from you table 'users' but in order to proceed I recommend creating a query where you use mysqli_query an select the $sql and $conn as parameters. In all honesty it is much advised to stop and continue once you have adapted to mysqli. Alternatively you can use PDO which in some cases can be seen as better to use rather than mysqli but the choice is yours. I personally would get to grips with mysqli and then look at some answers on Stack Overflow to decide whether you should use PDO or not. Visit the PHP manual here. Enter all the mysql functions you know and it will show you how to use the new mysqli version of the functions. Don't think that it is as simple as just adding and 'i' to the end of a mysql function. That's what I initially thought but there is alot to do with extra parameters etc. Hope this helps :-)

mysqli to pdo simple select statement

I just converted some MySQL to mysqli, but realized I do not have access to the mysqlnd driver with my server setup. So, I need to now convert to PDO which I have available.
I am trying to convert the following to PDO, but there is no bind_result available in PDO from what I have read. I need to use a prepared statement for this as there is user input.
$stmt = $mysqli->prepare("SELECT user,pass FROM test_users WHERE user = ?");
// bind params
$stmt->bind_param('s', $_POST['username']);
// execute prepared statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($ruser, $rpass);
// fetch values
$stmt->fetch();
// close statement
$stmt->close();
Can anyone help out quick? Here is what I have, but not sure how to retrieve the resulting values into useable variables...
$stmt = $db->prepare("SELECT user,pass FROM test_users WHERE user = ?");
// bind params
$value = $_POST['username'];
// execute prepared statement
$stmt->execute($value);
// stmt now holds results, but how can I retrieve them into useable values?
// ?
// close statement
$stmt->closeCursor();
You need to make yourself familiar with arrays. They are no less "useable" than regular variables.
And sometimes arrays even more usable, especially in your case.
$stmt = $db->prepare("SELECT user, pass FROM test_users WHERE user = ?");
$stmt->execute([$_POST['username']]);
$row = $stmt->fetch();
Now $row contains the row returned by query. Now you can test if any data returned and then use it.
For the password check you can use it this way
if ($row && $row['pass'] === whatever_hash_used($_POST['password']]))
{
unset($row['pass']);
$_SESSION['user'] = $row;
// etc
}
You can return values from a PDO query with the PDOStatement::fetch method. There are various ways of fetching the data, such as into an array, into an object, and into a lazy-loading object. The simplest of these, and the most appropriate in your circumstance, is an array. In this case, you need to use the PDO::FETCH_ASSOC constant.
$results = $stmt->fetch(PDO::FETCH_ASSOC);
You can then access $results['user'] and $results['pass'].
A nice way of improving this would be to fetch $user and $pass variables rather than an array. This can be done with the list construct:
list($user, $pass) = $stmt->fetch(PDO::FETCH_NUM);
The other problem with your code (as Your Common Sense may or may not be pointing out in the comments: it's a little hard to tell) is that your code to bind the variables isn't quite right. PDOStatement::execute expects an array:
$stmt->execute(array($value));
$stmt->execute([$value]); // from PHP 5.4
In my opinion, the nicer way to do this is with named parameters:
$stmt = $db->prepare('SELECT user, pass FROM test_users WHERE user = :user');
$stmt->bindParam(':user', $_POST['username']);
$stmt->execute();
list($user, $pass) = $stmt->fetch(PDO::FETCH_NUM);

Parse json object from table via php connected to phpmyadmin

I'm using a json-parser in Xcode to fetch a table from phpmyadmin. The parser gets (or should get) the json-formated document via a php-file uploaded on my ftp-server. The file is successfully parsed but it doesn't recognize any objects. I think this is because there are multiple arrays in the json-document.
When there's only one entry the document looks like this:
[{"id":"1","Name":"Eric","Message":"first from web"}]
but when i add an entry it looks like this:
[{"id":"1","Name":"Eric","Message":"first from web"}]
[{"id":"1","Name":"Eric","Message":"first from web"},{"id":"6","Name":"Claes","Message":"Hurrburr"}]
As you can see the old array (containing only the single entry) is still there in the second array with both entries.
I suspect the problem is that the old arrays are still there when i update the database because when i tried parsing the json document with only one entry (only one array) it worked.
So my question is first if thereĀ“s something i missed in my code, or if you know why the old arrays are still there when I update the database or how to remove all previous arrays when the document is updating.
Here is my .php-file:
<?php
$username = "perhaps not sharing this information";
$password = "or this";
$database = "nah";
mysql_connect("the server url",$username, $password);
#mysql_select_db($database) or die("Error here");
$query = "SELECT * FROM debug_db";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_numrows($result);
mysql_close();
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
echo json_encode($rows);
}
?>
And check out the json-document at: http://app.levinnovation.se/getjson.php
Thank you!

Joomla Database - How to use LIMIT in getQuery?

I want to build the below query using joomla inbuilt database class.
SELECT *
FROM table_name
ORDER BY id DESC
LIMIT 1
This is the query I have built up to now.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->nameQuote('*'));
$query->from($db->nameQuote(TABLE_PREFIX.'table_name'));
$db->setQuery($query);
$rows = $db->loadObjectList();
I don't know how to add the limit(LIMIT 1) to the query. Can someone please tell me how to do it? Thanks
Older than Joomla 3.0
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from($db->nameQuote('#__table_name'))
->order($db->nameQuote('id').' desc');
$db->setQuery($query,0,1);
$rows = $db->loadObjectList();
$db->setQuery function takes 3 parameters. The first one being the query, then the start, then the limit. We can limit records as shown above.
Newer than Joomla 3.0
setLimit(integer $limit, integer $offset)
If you want just one row
$query->setLimit(1);
Read more
This should work as well:
$query->setLimit(1);
Documentation: http://api.joomla.org/cms-3/classes/JDatabaseQueryLimitable.html
SetLimit doesn't work for me in Joomla 3.4.x, so try:
Within the model:
protected function getListQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
$query->from('#__your_table');
$this->setState('list.limit', 0); // 0 = unlimited
return $query;
}
Davids answer: https://joomla.stackexchange.com/questions/4249/model-getlistquery-fetch-all-rows-with-using-jpagination
Run that before the model calls getItems and it will load all the
items for you.
A few caveats with this.
You can also do this outside the model, so if for instance you were in
your view. You could do the following:
$model = $this->getModel(); $model->setState('list.limit', 0);
Sometimes you can do this too early, before the model's state has been
populated, which will cause the model to get rebuilt from the user
state after you have set the limit, basically overriding the limit.
To fix this, you can force the model to populate its state first:
$model = $this->getModel(); $model->getState();
$model->setState('list.limit', 0); The actual populateState method is
protected, so outside the model you can't call it directly, but any
call to getState will make sure that the populateState is called
before returning the current settings in the state.
Update: Just had to revisit this answer, and I can confirm, both the methods
setLimit & order are working if used as below.
$query->order($db->qn($data->sort_column_name) . ' ' . $data->sort_column_order);
$query->setLimit($length,$start);
OLD ANSWER
As of 08/Sept/14 The solutions from #Dasun or #escopecz arent working for me on J3.x
but this old trick is working for me which is nice,
$query->order($db->qn('id') . ' DESC LIMIT 25');
And About your specific requirement of wishing to fetch only 1 row you could use :
$rows = $db->loadObject();

PHP PDO succinct mySQL SELECT object

Using PDO I have built a succinct object for retrieving rows from a database as a PHP object with the first column value being the name and the second column value being the desired value.
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
I now want to apply it to a function with 2 parameters, the first containing the table and the second containing any where clauses to then produce the same result.
function select($table,$condition){
$sql = "SELECT * FROM `$table`";
if($condition){
$sql .= " WHERE $condition";
}
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
}
The idea that this could be called something like this:
<?php select("options","class = 'apples'");?>
and then be used on page in the same format as the first method.
<?php echo $option['green'];?>
Giving me the value of the column named value that is in the same row as the value called 'green' in the column named field.
The problem of course is that the function will not return the foreach data like that. That is that this bit:
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
cannot return data like that.
Is there a way to make it?
Well, this:
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
Can easily become this:
$sql = "SELECT * FROM `site`";
$site = array();
foreach( $sodb->query($sql) as $row )
{
$site[] = $row;
}
print_r($site);
// or, where 0 is the index you want, etc.
echo $site[0]['name'];
So, you should be able to get a map of all of your columns into the multidimensional array $site.
Also, don't forget to sanitize your inputs before you dump them right into that query. One of the benefits of PDO is using placeholders to protect yourself from malicious users.