PHP Creating variables list from Mysql database - php

I've a database that using for 3 languages this way:
id name de_de al_sq
1 title titel titulli
2 points punkte pike
Now when in php $lang is set to 'al_sq':
$lang = 'al_sq';
I'm trying to generate variables using names of that language, in this case:
$langtitle = 'titulli';
$langpoints = 'pike';
Trying something like:
$sql = "SELECT * FROM `langs`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$lang{$row["lang"]} = $row[$lang];
}
}
but something is not good, how to generate these variables?

You have a minor syntax error in your code, which causes an error. What you need to do here is to:
Fetch the name and al_sq columns from the database table. This is done by selecting the value of $lang (based on your code). For security reasons, the value of $lang is protected against SQL injection, as you did not specify where the value was coming from.
Then you must check if there was any results, and in the case there wasn't any, it will simply terminate the script with an error.
Then lastly you must iterate over each row of the returned results, and do a variable variable assignment. This will make $langpoints etc. work (and any other you may add in the future).
Code:
$sql = 'SELECT `name`, `' . $conn->real_escape_string($lang) . '` FROM `langs`';
$result = $conn->query($sql);
if (!$result || !$result->num_rows) {
echo 'Invalid language selected';
exit;
}
while ($phrase = $result->fetch_assoc()) {
${'lang' . $phrase['name']} = $phrase[$lang];
}
// $langtitle
// $langpoints

It seems you are using the database as a key-value store with multiple value fields depending on the language, you could use PDO::FETCH_KEY_PAIR so it returns an array with the name as the key. This way you also avoid loading the data for other languages that you might not need at all:
$query = "SELECT `name`, :column as value FROM `langs`";
$statement = $pdo->prepare($query);
$statement->execute(["column" => $lang]);
$data = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
// $data becomes an array with the name as the key:
$langtitle = $data['title'];
$langpoints = $data['points'];
Make sure, if the user provides the value for $lang, to check that it is a valid column value.

This should be close to what you are wanting based on how your database is presented. Scaling up would be clunky though if there is more the title and points stored.
$lang = 'al_sq';
$sql = "SELECT $lang FROM 'langs'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$langtitle = $row[1];
$langpoints = $row[2];
}
}

Related

Storing database results to a variable in PHP

I am trying to store the result from a MySQL statement for later use in PHP. I have this code which gets me the result:
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
}
}
So I know i will have the results in $row["id"] and $row["name"] and I want to save all of the rows so whenever i need them i can loop through them and for example echo them. I have searched for structures and arrays for keeping them in PHP but I cannot seem to find any information about that or maybe I am not searching in the right direction. Can anyone point me where i should read about this to find out how to do this efficiently and if possible post a small example?
Use sessions:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
$_SESSION['category_' . $row['id']] = $row['name'];
}
}
Then access it later from a different page
$_SESSION['session_variable_name']
You can also create an array of the information and store the entire array in a single session variable.
Just make sure you add the session_start function at the beginning of each page. The if statement prevents you from trying to start it multiple times.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
while ($row = $result->fetch_assoc())
{
$categories[$row['id']]=$row['name'];
}
}
And If you want the name anywhere use below :
$categories[$id]

php select query for one results and assign that value for a variable

I want to get only one record from using my select query and I want to assign that record for some variable how to do it?
$sql = "SELECT ccode FROM customer where ccode='".$ccode."' ";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $cc = isset($Row[0]) ? $Row[0] : '';
}
}
else {}
echo $cc;
if(102310 != $ccode)
{
$query = "insert into customer(ccode,name) values('".$ccode."','".$name."')";
$mysqli->query($query);
}
else
{
}
your code will fetch the data, the reason you are not getting an output is that you have mis-typed your variable name isset($Row[0]) ? $Row[0] : ''; should be isset($row[0]) ? $row[0] : '';
You would be better using a fetch column as you only want a single result.
What you really need to do is secure your SQL code from injection, you should never be adding variables directly into a statement. I'd suggest this as a good starting point: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
-- update --
It's worth noting I'm assuming here that ccode in your database is unique, so you there is only 1 that would equal your value. Otherwise you will need to add a limit as suggested in the comments, or some more criteria

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Multiple PHP dynamic variables displaying other dynamic variable values

I am generating dynamic variables like so:
$testPMA = '';
$result = mysql_query("SELECT * FROM site_pma") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
${$testPMA.$row['id']} = $row['value'];
}
$testLocation = '';
$result = mysql_query("SELECT * FROM site_location") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
${$testLocation.$row['id']} = $row['value'];
}
then I try displaying them like so:
if(isset(${$testPMA.$row_bom_lines['pma']})) echo ${$testPMA.$row_bom_lines['pma']};
The first one returns correctly. The next column and any after always take their id number for the dynamic variable, but only generate PMA. They never update to show Location or any other one I have created. I even tried mysql_free_result($result); after each one. How do I get the dynamic variable to display each of their own vs displaying the same table information for each column, just with an updated id number?

Looping through MySQL results and saving values to a $_SESSION

I am trying to store each column name in my database into its own $_SESSION. For example, say my column names are column_one, column_two, column_three, column_four, and column_five. I want these to be stored in a $_SESSION like $_SESSION['column_one'], $_SESSION['column_two'], etc. I am trying to do this in a loop but I have not been successful. How would I setup the loop to achieve this?
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);
if ($num == 1) {
//User was found
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$_SESSION['user_id'] = $row['user_id'];
}
}
Could you try this:
$id = mysqli_real_escape_string($dbc,$id);
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num= mysqli_num_rows(result);
if ($num == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['UserData'] = $row;
}else{
//handle error or user not found
}
echo '<pre>';
print_r($_SESSION['UserData']);
echo '</pre>';
You don't have necessity of use while or another loop, so is just one row
Something like this should work:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach($row as $column => $value) {
$_SESSION[$column] = $value;
}
}
Extra advice for safeguarding against SQL injection, the following two lines:
$id = mysqli_real_escape_string($dbc, $id);
$query = "SELECT * FROM table WHERE user_id = '$id'";
Update:
Thanks to EmilioGort who pointed out the missing connection parameter in mysqli_real_escape_string. See mysqli_real_escape_string docs.
While the other answers proposed a way to do, I'd strongly propose to not do this at all. Why?
First of all $row contains all details of the user in a well defined array form. It is generally good to keep this structure well prepared.
More important: Flattening $row might force name clashes like so:
Suppose $row has a property userName and somewhere else in your application you eventually set
$_SESSION[ 'userName' ] = $newUserName;
The new assignment to $_SESSION[ 'userName' ] might unintentionally change the property saved during the login process.
You might argue "Right now, my code doesn't use userName in $_SESSION'. Right! Unfortunately, you might use just this name for something else many month later on...
A better solution
I'd save the user detail like this:
$_SESSION[ 'sys$userDetails' ] = $row;
Imagine the prefix sys$ as being an indicator for framework generated properties of your session.
Thus, business logic related session data shouldn't have the sys$ prefix.

Categories