I have this PHP function that I want to use to retrieve a column, "username", from a table called "members". I have used the below function before, and had no problems. But now when I try to use it on a different project it won't work.
Here is the "functions.php" page code:
<?php
include 'connection.php';
function getusername(){
$query = "SELECT `username` FROM `members` WHERE `ID`=`".$_SESSION['user_id']."`";
if($result = mysqli_query($con, $query)){
while($row = mysqli_fetch_assoc($result)){
return $row['username'];
}
}
mysqli_free_result($result);
}
?>
On my login.php page I have a session variable that stores the user ID from the table in "$_SESSION['user_id']". I have echoed out the user ID so I know that the user ID is set.
On the page that I want the username echoed to, I have this snippet of code:
<?php echo getusername();?>
I also have the functions.php page "included" on the page where I want the username echoed to.
Your $con isn't set inside your function, so mysqli won't work. Additionally you're using backticks around the value you're searching for $_SESSION['user_id'] backticks are for column names, you should use ' around values.
try it like this:
<?php
include 'connection.php';
function getusername($con){
$query = "SELECT `username` FROM `members` WHERE `ID`='".$_SESSION['user_id']."'";
if($result = mysqli_query($con, $query)){
$row = mysqli_fetch_assoc($result);
mysqli_free_result($result);
return $row['username'];
}
}
?>
Then call it passing $con to the function:
$username=getusername($con);
On a side note your mysqli_free_result doesn't work if there are results as the return will stop the function. I updated the function a bit for it to work as you expect.
Related
Before setting as duplicate, I've spent 4 hours on researching about my problem, but I had no luck.
I am trying to make a signup/login system for my website. The main point that doesn't seem to work is that when I am signing up on my website, the session doesn't seem to start. The reason that I can see it is because, on my navbar, I have set it to change from signup to log out. Here is the piece of code for that:
<ul>
<li class="list1">Home</li>
<li class="list2">About</li>
<li class="list3">Portfolio</li>
<li class="list4">Blog</li>
<li class="list4">Contact</li>
<?php
if (isset($_SESSION['id'])){
echo "<li><a href='#'>SIGN OUT</a></li>";
}
else{
echo "<li><a onclick='signup(event)' href='#'>SIGN UP</a></li>";
}
?>
</ul>
To make that I have created three files. One is the mane page, one is the signup file itself, code below:
<?php
session_start();
include "../dbh.php";
$first = $_POST["first"];
$last = $_POST["last"];
$uid = $_POST["uid"];
$email = $_POST["email"];
$pwd = $_POST["pwd"];
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION['id'] = $row['id'];
header("Location: ../index.php");
exit();
and the last one is the file which connects PHP to the database code below:
$conn = mysqli_connect("XXX","XXX","XXX","XXX");
if (!$conn){
die("Connection failed: ".mysqli_connect_error());
}
I believe that the session doesn't start because the main page reloads after the user hits signup on the form, but I have started the session on all of my files (except the database connection file where it's not needed). I used session start on all of my page and I placed it on the beginning of all pages with opening and closing PHP tags.
Any suggestions? I appreciate your answers and comments!
Sorry for the bad English but it's not my first language.
This:
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
^^^^^^^^^^^^^^^^^^
$_SESSION['id'] = $row['id'];
Insert queries do NOT return a result set, and you can NOT fetch() from them. That means mysqli_fetch_assoc() is failing, and returning a boolean FALSE. You then use that boolean false as if it was an array, and are basically doing the equivalent of
$_SESSION['id'] = null;
Note this:
php > $foo = false;
php > $id = $foo['id'];
php > var_dump($id);
NULL
You want
$_SESSION['id'] = mysqli_insert_id($conn);
instead.
It is an error with you SQL query.
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
The first line of the code is an INSERT command. The second line executes this command by sending it to the server. If query is properly processed then MySQL server doesn't return you anything, so $result will equal to true. It wil not contain any data from the database. So you can't fetch it, what you try to do in the third line. Need to make a separate query for data.
i am having a problem with the get method in php, i try to get a variable($profile_id) from one php page to another, the variable is working in this page
<?php
$follow="";
$loggedinid=$_SESSION['userid'];
$sqll = "SELECT id FROM Follow WHERE user_one='$loggedinid' AND user_two='$profile_id'";
if($profile_id != $_SESSION["userid"]){
$check= mysqli_query($db_conx, $sqll);
if(mysqli_num_rows($check) == 1){
$follow='Unfollow';//This is where i try to put the variable, so i can call it with the get method on followaction.php
}else{
$follow='Follow';
}
}
?>
but then in the followaction.php when i call the profid, It returns $profile_id(sting) instead of the number it should be representing
<?php
include_once("php_includes/check_login_status.php");
$followaction=$_GET['followaction'];
$profileid = $_GET['profid'];
$loggedinid = $_SESSION['userid'];
$loggedinusername = $_SESSION['username'];
if($followaction == 'follow'){
mysqli_query($db_conx, "INSERT INTO Follow VALUES('','$loggedinid','$profileid')");
}
if($followaction == 'unfollow'){
$sql = "DELETE FROM Follow WHERE user_one='$loggedinid' AND user_two='$profileid'";
mysqli_query($db_conx, $sql);
}
?>
How can i fix this, everything is working but i cant transfer the profile_id to this page....
This does not work
$follow='Unfollow';
If you do
echo $follow;
You will get something like this (Notice $profile_id has not been replaced)
Unfollow
You need to use double quotes if you want variable replacement
$follow="Unfollow";
<?php
require ("db/db.php");
$c_id = ($_POST['c_id']);
$c_title = ($_POST['c_title']);
$c_content = ($_POST['c_content']);
// echo place
$sql = mysql_query("UPDATE content
SET c_id = $c_id, c_title = $c_title, c_content = $c_content
WHERE c_id = $c_id");
header("location: index.php");
?>
This is my code.
when the header goes to the index, nothig has changed in the fields that are presented here.
i tried to echo the variables at the "echo place" and they all returned correct,
so i know that they are POSTed to the page.
i guess the error are in the SQL UPDATE statement, but PHP does not return any error to me,
it just goes directly to the index.php.
when i try to run the SQL in phpmyadmin, whith value 1 instead of the variable, it changes all the fields to 1, so there it works.
1) You should use mysql_real_escape_string()
2) why your are updating the id of a table? you also need to change your query
3) use quotes in your php variable
Try like this:
require ("db/db.php");
$c_id = mysql_real_escape_string($_POST['c_id']);
$c_title = mysql_real_escape_string($_POST['c_title']);
$c_content = mysql_real_escape_string($_POST['c_content']);
// echo place
$sql = mysql_query("UPDATE content
SET c_title = '$c_title', c_content = '$c_content'
WHERE c_id = $c_id limit 1") or die(mysql_error());
header("location: index.php");
You should switch to mysqli or PDO since mysql_* are outdated and will be removed.
Just to be sure, try this code (As I don't know the variables content, I put all of those with "'"
$sql = <<<SQL
UPDATE content
SET c_id='{$c_id}', c_title='{$c_title'}, c_content='{$c_content}'
WHERE c_id='{$c_id}'
SQL;
$query = mysql_query($sql);
var_dump($query);
And if the $query returns true, put the header('Location: index.php"); again
I am new to PHP and just wanting to make a basic page where i can see all the users in the database and delete them. I have come this far but it keeps on telling me that I have an i have and Undefined index: user_id and although it tells me that it has deleted the fields it has not deleted anything. Here is my code:
<?php include_once "includes/scripts.php"; ?>
<?php include_once "includes/connect.php";?>
<?php include_once "includes/cms_page_security.php";?>
<div id="cms_container"><br>
<br>
<h1>MANAGE USERS<img src="images/three_column_grid_line.png" alt="line"></h1>
<p class="logout_btn">Back</p>
<?php
$tbl="users"; // Table name
$sql = "SELECT * FROM $tbl";
$result = mysql_query($sql, $connect);
while($rows = mysql_fetch_array($result)){
?>
<?php
echo $rows['user_id'];
echo $rows['user_name'];
echo $rows['user_password'];
?>
delete
<?php
}
?>
<?php
mysql_close();
?>
</div><!--cms_container-->
</body>
</html>
The page that it should link to that deletes the query:
<?php include_once "includes/connect.php";?>
<?php
$tbl="users";
$user_id= $_GET ['user_id'];
$sql="DELETE FROM $tbl WHERE user_id = '$user_id'";
$result = mysql_query($sql, $connect);
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='delete.php'>Back to main page</a>";
}else {
echo "ERROR";
}
?>
<?php
mysql_close();
?>
In delete_user.php you must get user_id
$user_id= $_GET ['id'];
because in your delete link GET variable is "id", not "user_id"
You really should be using PDO instead.
The issue is in the information that you are passing.
The link : delete
is looking for an 'id' but you're later looking for 'user_id'
If you change it to delete, it should work.
I still strongly suggest you look into PDO instead though, it's much more secure and easier to work with.
Example of PDO Delete
public function deleteUser($username, $user_id){
if($this->isAdmin($username) == true){
$query = $this->db->prepare('DELETE FROM users WHERE user_id = ?');
$query->bindValue(1, $user_id);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}else{
return false;
}
}
I'm running an extra check to make sure the person who is requesting the deletion is an admin member but you should be able to see the structure
In addition to the other answers:
It looks like this line could be a fatal error, if php short tags aren't enabled:
delete
The php manual says:
*PHP also allows for short tags <? and ?>
(which are discouraged because they are only available if enabled with
short_open_tag php.ini configuration file directive, or if PHP was configured
with the--enable-short-tags option.*
http://php.net/manual/en/language.basic-syntax.phptags.php
The SQL query will be successful even if it alters zero rows. You are prefixing your user ids with a space when you are generating your HTML (id= <?), so you aren't matching any rows (since "1" won't be matched by " 1").
Where you are creating your 'Delete' link
delete
You're creating a variable of 'id', but later you look for 'user_id.
Change your link to
delete
I really got a problem now. I tried for decades and I can't find why it is not working. I want to get the user that is logged in to see their email on a specific page. I tried a new code now and i get this error: Notice: Undefined variable: row in
The code I use is:
<?
$username = $_SESSION['username'];
$sql = "select * from users where username=" . $username . "";
echo $sql;
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
}
?>
AND
<?php echo $row['email']; ?>
<?php
$username = $_SESSION['username'];
$query = mysql_query("select * from users where username='".$username."'");
while ($row = mysql_fetch_array($query)) {
$email=$row["email"];
}
echo $email;
?>
try this.
don't use mysql_* functions
I think... Problem is in SQL query. I propose your column "username" is something like VARCHAR(50). So you have to add quote.
$sql = "select * from users where username='" . $username . "'";
I see a bug, and a design problem.
You've designed your script so that you're printing whatever was last assigned to $row in the condition of your while loop.
You're getting the error because the query is not returning anything and the loop is not running. Therefore, $row is never assigned. That being said, you probably don't want to use a while-loop if all you're trying to do is display the value of the "email" column in the first record returned. If you did want to, then stop it.
Call mysql_fetch_assoc() on your $result (doesn't return as much data), and check that it doesn't return FALSE (one or more records weren't found).
if((row = mysql_fetch_assoc($result)) === false)
die("Error.");
?>
Email: