Passing two php variables to another page from a link - php

Ok so I'm building a simple question/answer site and this is a loop that outputs all the questions asked previously in link form. I'm trying to concat two variables to the next page url so I can get them and work with them there but it will only allow one? I've tried everything but not working? See the only comment section of my code for the crux of the issue. Thank you.
<?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;
$conn = mysqli_connect($servername, $username, $password, $dbname,
$port);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'> Log out </a><br>
<a href='ask.php'> Ask a question</a><br>
<br />
<br />";
echo "Answer another users question: <br><br />";
$sql = "SELECT q_id,question, username FROM questions";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result))
{
$q_id = $row['q_id'];
$question = $row['question'];
$username = $row['username'];
//right here I need to add(concat) the second variable $username
//I need to get both on the next page url but not allowing me to
echo ('<a href="totalqs.php?q_id=' . $q_id .' " >' . $question .
'</a>' . '<br>');
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

Try this (assuming that $username has a value):
echo ('<a href="totalqs.php?q_id=' . $q_id .' " >' . $question . " Username:" . $username . '</a>' . '<br>');

It looks like you're doing HTTP GET so instead of trying to concat 2 strings, why not just have something like
totalqs.php?q_id=$q_id&question=$question&username=$username
Then in the totalqs.php, you'll do something like
$q_id = $_GET['q_id'];
$question = $_GET['question'];
$username = $_GET['username'];
This is assuming you have access to totalqs.php.

You can send to variables by adding the & and then continuing to add values.
Example
example.php?one=value&second=value
In your case
totalqs.php?q_id=$q_id&username=$username

Use this code in your echo statement. This concatenates your second value $username with name user:
echo ''.$question.'<br />';
Note that you do not need parentheses in your echo statement. You need to properly concatenate your string (you need to learn more about concatenation). In the next page, you can access q_id and user as
$id = $_GET['q_id'];
$username = $_GET['user'];

Get requests can pass multiple variables for example: {host}?var1=val1&var2=val2&var2=val3
You could echo out a link with a get request in it:
echo ('<a href="totalqs.php?q_id=' . $q_id .'&username='. $username .'" >' . $question .'</a>' . '<br>');
And then, you could use $_GET to retrieve these vars in totalqs.php. Like:
$_GET['username']
would give you the value of the username.

Related

How do I get all values to echo with mysqli_fetch_assoc?

I'm pretty new to php, so don't really know how to do much, but from what I've looked up, this should echo all values from the two fields.
<?php
$con = mysqli_connect('localhost', 'root', 'root', 'unityaccess');
if(mysqli_connect_errno())
{
echo "1: Connection failed"; //error code 1 = connection failed
exit();
}
$username = $_POST["name"];
$idcheckquery = "SELECT id FROM users WHERE username = '" . $username . "';";
$idcheck = mysqli_query($con, $idcheckquery) or die("7: ID check query failed"); //error code 8 = couldn't get user's id
$existingid = mysqli_fetch_assoc($idcheck);
$userid = $existingid["id"];
$itemfindquery = "SELECT itemid, equipped FROM inventory WHERE userid = '" . $userid ."';";
$itemfind = mysqli_query($con, $itemfindquery) or die("9: Couldn't find items");
while($row = $mysqli_fetch_assoc($itemfind)){
echo $row["itemid"] . ", " . $row["equipped"] . " ";
}
?>
I expect this to, when it is called in unity, to print a list of all the values in each list, but instead it doesn't echo anything.
The mysqli_fetch_assoc() function is being used as a variable ($). Just remove the dollar sign and it will work.
while($row = mysqli_fetch_assoc($itemfind)){
echo $row["itemid"] . ", " . $row["equipped"] . " ";
}
Also, try to use prepared statements to fight against SQL injections.

Get Table info for Sessioned Users

I've made a simple login system that uses PHP to talk to mysql and start a session.
On my page accessable only to those with an active session, I'd like to display some information about the user to the user. I have a mysql config php page, a logon page, and a registration page.
I've found a great example, but it doesn't work in my code. I've changed some things to match my database, and session that was started by the logon page. What could I be doing wrong?
<?php
$sql = "SELECT fname, lname FROM users WHERE username = '" . $_SESSION['username'] . "'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo "Hello, " . $row['fname'] . " (" . $row['lname'] . ").";
?>
I've even tried:
<?php
echo $_SESSION['username'];
?>
Which doesn't work either.
You need a link to the database first, and secondly mysql is deprecated, use mysqli instead. Also take a look at prepared statements against SQL injection.
<?php
$servername = "Servername";
$username = "Username";
$password = "Password";
$database = "Database";
$link = new mysqli($servername, $username, $password, $database);
$sql = "SELECT fname, lname FROM users WHERE username = '" . $_SESSION['username'] . "'";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($result)){
echo "Hello, " . $row['name'] . " (" . $row['email'] . ").";
}
?>
if you are not getting results when
<?php
echo $_SESSION['username'];
?>
That means either you have not assigned a value to $_SESSION['username'] or haven't used session_start() on top of it.
try like this,
<?php
session_start(); //on top of everything
echo $_SESSION['username'];
?>

how can i get a variable value into a select tag in html using php

so the line of code
echo "<option value = '$name'>$name</option>";
is where i am having a problem. I am trying to get drop down menu to have the values of every name in the database. here is my code, it is in a html file:
<select name = "author" id = "author">
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$database = "db";
$con = mysqli_connect($servername,$username,$password,$database);
if($con->connect_error){
die("Connection failed " . $con->connect_error);
}
$sql = "select first, last from Employee";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
$name = $row['first'] . ' ' . $row['last'];
echo "<option value = '$name'>$name</option>";
/*echo <<<EOT
<option value = '$name'>$name</option>"
EOT;*/
}
?>
</select>
I have tried it using a normal string, and as an EOT. Currently when i look at the html page it shows "$name" instead of the actual name. I have done output testing and $name is storing what i expect it to store.
I just take a step in the dark, You saved your file as HTML (.html) and not as a PHP file (.php)?
Try:
echo "<option value = '".$name."'>".$name."</option>";
or
echo "<option value = '{$name}'>{$name}</option>";
I remember there being something about PHP not processing variables between single quotes. The best way may be to break and concat the string
echo "<option value = '".$name."'>$name</option>";

converting from array to string, implode didnt work

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "comp4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id , First_Name, Last_Name FROM member WHERE username='tracy'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["First_Name"]. " " . $row["Last_Name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I have this code in order to display some details about a member in my database but I want to make it into a string and a variable, I tried to use the php implode function but I recieved an error saying that some of the other variables were unexpected any tips or anything wrong that im doing?
Where you used implode()
`<?php
$id = $row["id"];
$first_name = $row["First_Name"];
$arr=array ($id,$first_name);
echo implode(" ",$arr);
?>`
In your while loop, you should first concatenate all your column in one array, to be then collapsed in one single string as following :
while($row = $result->fetch_assoc())
{
// temp variables
$id = $row["id"];
$first_name = $row["First_Name"];
$last_name = $row["Last_Name"];
$array = array($id, $first_name, $last_name); // creating an array
$result = implode(" - ", $array); // Collapsing data using dash
printf($result); // displaying data collapsed
}
from official php implode doc
I you want the result in a string, replace the echo by this:
$results .= "id: " . $row["id"]. " - Name: " . $row["First_Name"]. " " . $row["Last_Name"]. "<br>";
Now everithing is in $results
Here is perfect solution for your problem.. It will work. i am using mysql extension rather than mysqli..

Username and ID change after i search for something

I have a small social website, with profile pages and a search page. It all works fine and on the menu bar it displays the users username with a link to their profile via profile.php?id=5 (for example).
How ever when I search for something via search.php it all works fine, but then when I reload a page after searching, suddenly the username is displayed as 'p' and the link goes to profile.php?id=p
Does anybody have any idea what's happening?
Tell me if you need any more information, and thanks in advance.
The code:
<?php
//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_GET['search']);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
//database connection info
$host = ""; //server
$db = ""; //database name
$user = ""; //dabases user name
$pwd = ""; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT * FROM users WHERE username SOUNDS LIKE '%$searchTerm%' or fname SOUNDS LIKE '%$searchTerm%' or lname SOUNDS LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
echo "<div class='searched'>Results for ";
echo $searchTerm;
echo "</div>";
/* check whethere there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
$output .="<div class='user'><a href='profile?id=$row[id]'>";
$output .= "<img class='search_pp' src='" . $row['picture'] . "'/><br>";
$output .= "<div class='search_username'> " . $row['username'] . "</div>";
$output .= "<div class='search_full'>Full name: " . $row['fname'] . " " . $row['lname'] . "</div>";
$output .= "<div class='search_sex'>" . $row['sex'] . "</div></div></a>";
}
echo $output;
}
else
echo "No records of " . $searchTerm;
?>
This is where the username changes to 'p'
<?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>
and this is where the id in a link changes to 'p'
<a href="profile?id=<?php echo htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8'); ?>">
then the users username and id changes to 'p' all throughout the site
1 - WHere do you set your $_SESSION['user'] ?
2 - Can you do a var_dump($_SESSION['user']); before and after the refresh to see what's going on?

Categories