PHP: How to store dynamic variables within session variable? - php

Here is what I'm trying to do:
$username = 'john';
$_SESSION['data'] = "Hello ".$username;
$username = 'mike';
$new = $_SESSION['data']; // trying make it like: $new = "Hello ".$username;
echo $new // should output: "Hello Mike"
I'm trying to save a phrase with a dynamic variable into a $_SESSION variable, so the phrase can later be change on a different page depending on the dynamic variable.
Is this possible, and how can it be done?

You could use string formatting for that. Take a look:
$username = 'John'; // not really needed for this test
$_SESSION['data'] = "Hello %s";
$username = 'Mike';
$text = sprintf($_SESSION['data'], $username);
echo $text
Output:
Hello mike
See the code in action here.

It will not work the way you have it written, because the value you have stored in the session is a completely new value made using the value of the $username variable. As soon as it has been created, the value in the session is not associated with the $username variable whatsoever.
You can store the name and the phrase in the session separately, so they can be modified independently, and then combine them together later at the time you need to use them together.
For the specific case in your comment, storing the SQL string for a prepared statement with placeholders should work.
$_SESSION['statement'] = "SELECT some_columns FROM some_table LIMIT ?, ?";
$_SESSION['limit'] = $limit;
$_SESSION['offset'] = $offset;
You can't store the prepared statement itself, but you can store the SQL string, and then prepare and execute it in subsequent pages.
$stmt = $pdo->prepare($_SESSION['statement']);
$stmt->execute([ $_SESSION['limit'], $_SESSION['offset'] ]);
Just remember when you are ready to bind values to it on your next page before executing it that you need to specify that they should be bound as integers or disable emulated prepared statements.

If you want to add new element in the session array then you can push new element in the session array as follows:
array_push($_SESSION['data'],$element)

You could do something like this:
$username = 'john';
$_SESSION['data'] = 'echo "Hello $username";';
$username = 'mike';
eval($_SESSION['data']);
But I don't know why you'd want to, there are millions of ways you could achieve the results you want, an approach like this probably isn't the best.

Related

How to combine the $_SESSION into one variable in PHP mysqli ?

normally, i use the single $_SESSION for single field in the table as below in mysqli, let's say i use 'email' field in users table
$email = mysqli_real_escape_string($connect,$_POST["email"]);
$_SESSION['email'] =$email;
but it only can use email as sessions right ?
But what if i have multiple fields in the users table such as username, password, gender ?. How to combine/bind all the $_SESSION fields together into one variable ?
$user = $sessions_variable['username'];
thanks in advance :)
$_SESSON is an array. So your first move is to read up on arrays in the PHP manual.
After that you'll be able to either assign different values to different $_SESSON elements
$_SESSION['email'] = $email;
$_SESSION['username'] = $username;
or, after getting the user info from a database, assign it to a single element
$_SESSION['user'] = $row;
You can create multidimensional array in session like this
$_SESSION['user']['username'] =$username;
$_SESSION['user']['email'] =$email;
then you can pass whole user session array to single variable.
$user = $_SESSION['user'];
We can create multidimensional array for session follow the below procedure.
Example:
$_SESSION['foo']['foo_1'] =$foo1;
$_SESSION['foo']['foo_2'] =$foo2;
$_SESSION['foo']['foo_3'] =$foo3;
...
Now if we want to use whole foo array in single variable. you have to pass it like this.
$foo_whole_session = $_SESSION['foo'];
You can check what you found using print_r($_SESSION).

Use variable inside a call?

Is there a way to make this happen? I mean where the stage == to a variable?
$var1 = "1";
$var2 = "2";
$where = $db->query('SELECT * FROM stages WHERE stage = $var1');
$chapter = $where[0]["$var1"];
Edit: Got told to give more information.
When I try to run this I get a php error for the databaseProvider and nothing happens. If I write
$where = $db->query('SELECT * FROM stages WHERE stage = 1');
$chapter = $where[0]["1"];
Everything works fine. I just want to be able to automate those two ones :)
If you use double-quotes instead of single-quotes then PHP will interpolate your variable for you:
$var1 = "1";
$var2 = "2";
$where = $db->query("SELECT * FROM stages WHERE stage = $var1");
But if $var1 is something that comes from user in put then you shouldn't do this to avoid SQL injection.
I'm unclear where your $where[0]["$var1"] was going... Do you mean to then use another variable? If so, you're looking for prepared statements using :var in PDO or ? in mysqli.

Store values in PHP

I have an object that has a single comment on it and then that object has subobjects that each can have a comment on it. As it is today I have a single variable to store the comment on the whole object and a list to store the comments for the objects subobjects.
public $TestResultComments = array();
public $Comment;
Now I not only want to store the plain text of a comment but also store the username of that person that has wrote it and the timestamp. So instead of the single variable $Comment I now want to store three. What is the best way to store this, into an array or is there something similar as in Haskell where there are Tuples?
$comment = odbc_result($result, "comment");
$userName = odbc_result($result, "username");
$timeStamp = odbc_result($result, "timestamp");
$testResult->Comment = $comment;//This is what I do today, but I also want to include $userName and timestamp here
The second part is where I store the comments for the subobjects.
for ($i = 1; $i <= $no_results; $i++) {
odbc_fetch_row($result, $i);
$type = trim(odbc_result($result, "result"));
$testResult->TestResultComments[$type] = trim(odbc_result($result, "comment"));//Here I aswell want to store "comment","username" and "timestamp" as they are called in the database table and not only "comment" as I currently do.
}
As you can see in the second example I have a keyvalue "result" to get the comment. Here I also want to get the values ("comment","username","timestamp") instead of a single value as today.
Thanks in advance.
Seems like a nice situation to use the stdClass. stdClass allows you to dynamically declare fields for an object. You have an array of these, with say result as the key.
Example
$allValues = array();
// Create the values.
$values = new stdClass();
$values->comment = $comment;
$values->username = $username;
$values->timestamp = $timestamp;
$allValues[$result] = $values;
This gives you a direct mapping from a $result to several values, in a clean and OOP way. In the future, assuming you've created $result, you can say..
$values = $allValues[$result];
echo "The username is ". $values->username;
I really like using it because it makes your code super clean and OOP in syntax. For loosely typed languages like PHP, readability can sometimes be lost so it's important you maintain practises like this to keep things easy to understand.

Getting information from MySQL

I'm having trouble getting info from my MySQL database.
Here is my code :
/********************
* Database Info
********************/
$host = "localhost";
$user = "admin";
$pass = "admin#";
$database = "db_admin";
/********************
* Database connection
********************/
$con = mysqli_connect( $host, $user, $pass, $database );
if (mysqli_connect_errno ()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}
$result = array();
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
$query = "SELECT * FROM Servers WHERE PID='" .$id. "'";
$result = mysqli_query($con, $query);
}
print("<pre>".print_r($result,true)."</pre>");
My first question, Did I use "isset" function currectly?
Because it doesnt seem like it is actually going though the if statement.
The Url I am using is : #..com/view.php?ID=1
My second question, Did I use the $query correctly?
Because I echo $id and that echoed out a "MySQL Object()"
Finally, the print printed out "Array()"
I'm just starting on PHP, Thanks for the help :)
A few things:
If you're passing the variable in the query string, use $_GET instead of $_POST to retrieve the values.
$result will return an pointer to the recordset, not the rows themselves. You will have to use mysqli_fetch_array() to fetch the rows.
ADD:
If you are sure that you will only have 1 record returning, you can use:
$row = mysqli_fetch_assoc($query);
echo $row['field_name'];
More then 1 record?
while($row = mysqli_fetch_assoc($query)){
echo $row['field_name'];
}
# your first question: if you have a input field with the name="ID", then its good.
Please also post your HTML :)
$var = 'Hello world';
if(isset($var)){ //If the var $var has been set (in this case it is)
echo $var;
} else {
//If $var is not set, then we get in the else
echo 'The var $var is not set';
}
The best thing is debugging the code with a debugger, you may use XDebug, or at least use var_dump(); to see what happens
var_dump($_REQUEST, $result);
Answer to your first question: It's hard to say if you've used it correctly when you haven't said what you're trying to do. I'm presuming that you only want run the code enclosed in the if-statement if the POST variable 'ID' has been received. If so, yes you've done it correctly.
Answer to your second question: I'm presuming on this line you're trying to build a string with a valid MySQL query. You've done that correctly, assuming $_POST['ID'] is a string (or can be converted to a string, see http://www.php.net/manual/en/language.types.string.php#language.types.string.casting).
If you're echoing $id and it's returning an object, however, you'll have a problem. You can't combine a string and an object like that. You'd need to iterate the object with a foreach, for example, and extract the id from that. The rest of the code won't work until that part is resolved.
The thing to investigate now is why $_POST['ID'] is returning an object. You'll need to provide the form code at the very least.

How to only update an sql table column if a variable is not empty with php?

I am getting my variables from form fields using php :
$url=$_POST['url'];
$tags=$_POST['tags'];
$skillArea=$_POST['skill_area'];
$description=$_POST['description'];
$slideshowImageFileName=($_FILES['imageNameSlideshow']['name']);
But when I run my sql insert query, I get an error if one of the variables is empty, so I have taken to write if statements to deal with this to rewrite the query string, but surely, that's not the answer? It seems very messy
if(empty($slideshowImageFileName)){
$query1="INSERT INTO portfolio (item_name,image_path,description,url) VALUES('$itemName','$imageFileName','$description','$url')";
}else{
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
}
I suppose you are looking for something like this:
$slideshowImageFileName = (isset($_FILES['imageNameSlideshow']['name']) && !empty($_FILES['imageNameSlideshow']['name'])) ? $_FILES['imageNameSlideshow']['name'] : NULL;
This will check if the name of the slideshowimage is set and not empty. if it is NULL will be assigned to the variable, if its correct the value will be assigned.
You could replace NULL with "" if you want an empty string to be added.
Try to set the value of $slideshowImageFileName to empty string or a single space as your database table will accept, and use the second query always.
if(empty($slideshowImageFileName)){
$slideshowImageFileName = "";
}
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
I am agreed with Mr. Ray. But there is another solution apart from that. Probably slideshow_image_path field on the table doesn't allow null. So you may change the attribute by allowing null and it will work.
I'd probably construct a builder if I'm sure I'll get a lot of optional data.
Like this:
$acceptedKeys = array
('item_name',
'image_path',
'description',
'url',
'slideshow_image_path');
$inserts = array();
foreach($_GET as $key => $var) {
if(in_array($key, $acceptedKeys)) {
// clean and validate your keys here!
$inserts[$key] = $var;
}
}
$customKeys = implode(array_keys($inserts), ',');
$customValues = implode($inserts, ',');
$query = "INSERT INTO portfolio ($customKeys) VALUES($customValues)";
There's a few options to this.
Simplest one is to make sure the variables are always set, even if not passed through:
//Set up your database connection as normal, check errors etc.
$db = mysqli_connect($host,$user,$password,$db);
$url = isset($_POST['url']) ? mysqli_real_escape_string($db, $_POST['url']) : "";
$tags= isset($_POST['tags']) ? mysqli_real_escape_string($db, $_POST['tags']) : "";
Escaping data is good practice :) In your INSERT query you'll still need to wrap the values in quotes, or you could do that in the above code as per your preference.
http://uk3.php.net/manual/en/mysqli.construct.php

Categories