/    Sign up×
Community /Pin to ProfileBookmark

JOIN mysql php

Sorry

on my userinfo.php page

it currently retrieves and displays the username and email address but now I want to retrieve and display the Full name of the visitor from the visitors table

I know it can be done using JOIN but not 100% sure how to code it in

I did try from another php file that uses JOIN but it only only displays the first letter of the full name

The code I have is below in the userinfo.php file

[code=php]
<?php
ini_set(‘display_startup_errors’,1);
ini_set(‘display_errors’,1);
error_reporting(-1);
?>

<?php
/**
* UserInfo.php
*
* This page is for users to view their account information
* with a link added for them to edit the information.
*
* Updated by: The Angry Frog
* Last Updated: October 26, 2011
*/
include(“include/session.php”);
global $database;
$config = $database->getConfigs();
if (!isset($_GET[‘user’])) {
header(“Location: “.$config[‘WEB_ROOT’].$config[‘home_page’]);
}
?>

<?php
$db = mysqli_connect(“” , “”, “”) or die(“Check connection parameters!”);
// Optionally skip select_db and use: mysqli_connect(host,user,pass,dbname)
mysqli_select_db($db,””) or die(mysqli_error($db));

if (mysqli_connect_error()) {
die (‘Failed to connect to MySQL’);
} else {
/*SUCCESS MSG*/
echo ”;
}

$sqlCommand3 = “SELECT v.visitor_id, visitor_name
FROM visitors v
JOIN users”;

$query = mysqli_query($db, $sqlCommand3) or die (mysqli_error($db));

//fetch the data from the database
while ($row = mysqli_fetch_array($query)) {

$visitor_name = $row[‘visitor_name’];

}

?>

<?php
$title = “My Account – The Tax Elephants”;

$pgDesc=””;

$pgKeywords=””;

include ( ‘includes/header.php’ );
?>
<!–CONTENT–>

<div id=”column-whole”>

<?php
/* Requested Username error checking */
$req_user = trim($_GET[‘user’]);
if(!$req_user || strlen($req_user) == 0 ||
!preg_match(“/^[a-z0-9]([0-9a-z_-s])+$/i”, $req_user) ||
!$database->usernameTaken($req_user)){
die(“Username not registered”);
}

/* Logged in user viewing own account */
if(strcmp($session->username,$req_user) == 0){
echo “<h1>My Account</h1>”;
}
/* Visitor not viewing own account */
else{
echo “<h1>User Info</h1>”;
}

/* Display requested user information – add/delete as applicable */
$req_user_info = $database->getUserInfo($req_user);

/* Username */
echo “<b>Username: “.$req_user_info[‘username’].”</b><br>”;

/* Email */
echo “<b>Email:</b> “.$req_user_info[’email’].”<br>”;

echo “<strong>Name:</strong> “.$visitor_name[‘visitor_name’].”<br>”;

/**
* Note: when you add your own fields to the users table
* to hold more information, like homepage, location, etc.
* they can be easily accessed by the user info array.
*
* $session->user_info[‘location’]; (for logged in users)
*
* $req_user_info[‘location’]; (for any user)
*/

/* If logged in user viewing own account, give link to edit */
if(strcmp($session->username,$req_user) == 0){
echo ‘<br><a href=”useredit.php”>Edit Account Information</a><br>’;
}

/* Link back to main */
echo “<br><a href=’process.php’>Logout</a><br>”;

?>

</div>

<?php
// Free the results
mysqli_free_result($query);

//close the connection
mysqli_close($db);
?>

<!–CONTENT–>

<?php include( ‘includes/footer.php’ ); ?>
[/code]

I have added visitor_id in the users table and made it INT(11) at the end of the users table and is currently saying 0 but the visitor_id of the user I am trying to match it with is 66

I looked in database.php as going by another php file using JOIN, it has INSERT INTO as well so it looks like it inserts the visitor_id into two two tables so I thought it already adds visitor_id into visitors table and thought it would also add visitir_id into the users table but has not worked that way

the database.php coding I have is below

[code=php]
function addNewUser($username, $password, $email, $token, $usersalt){
$time = time();
$config = $this->getConfigs();
/* If admin sign up, give admin user level */
if(strcasecmp($username, ADMIN_NAME) == 0){
$ulevel = ADMIN_LEVEL;
/* Which validation is on? */
}else if ($config[‘ACCOUNT_ACTIVATION’] == 1) {
$ulevel = REGUSER_LEVEL; /* No activation required */
}else if ($config[‘ACCOUNT_ACTIVATION’] == 2) {
$ulevel = ACT_EMAIL; /* Activation e-mail will be sent */
}else if ($config[‘ACCOUNT_ACTIVATION’] == 3) {
$ulevel = ADMIN_ACT; /* Admin will activate account */
}

$password = sha1($usersalt.$password);
$userip = $_SERVER[‘REMOTE_ADDR’];

$query = “INSERT INTO “.TBL_USERS.” SET username = :username, password = :password, usersalt = :usersalt, userid = 0, userlevel = $ulevel, email = :email, timestamp = $time, actkey = :token, ip = ‘$userip’, regdate = $time, visitor_id = $visitor_id”;
$stmt = $this->connection->prepare($query);
return $stmt->execute(array(‘:username’ => $username, ‘:password’ => $password, ‘:usersalt’ => $usersalt, ‘:email’ => $email, ‘:token’ => $token));
}
[/code]

to post a comment
PHP

9 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJun 28.2015 — It's hard to say without really understanding the table structures and how the two tables are related, but if it does indeed make sense to join those two tables in a query, you need to explicitly state the relationship via either an ON or USING() statement. If the common column that joins them has the same name, you can use USING()
<i>
</i>SELECT . . .
FROM table1
INNER JOIN table2 USING(joining_column_name)
. . .

If the common columns have different names, then:
<i>
</i>SELECT . . .
FROM table1
INNER JOIN table2 ON table1.some_column = table2.another_column
. . .

Hope that gets you going in the right direction.
Copy linkTweet thisAlerts:
@ianhaneyauthorJun 28.2015 — Hi NogDog

Thank you for the reply, appreciate it

In the database tables, the columns have the same name, in visitors the column is called visitor_id and in the users table, the column name is called visitor_id so used the first lot of coding you mentioned

[code=php]
SELECT visitor_id, visitor_id
FROM visitors
INNER JOIN users USING visitor_id
[/code]


Is that right?

as I am trying to get the visitor_name displayed, do I need to create a column in the users table called visitor_name as well or just visitor_id?
Copy linkTweet thisAlerts:
@ianhaneyauthorJun 28.2015 — Think I am getting somewhere slowly

I am using a online SQL tool http://sqlfiddle.com/ to get the query working first and seems to work in that tool

I got the following code

[code=php]
$sqlCommand3 = "SELECT visitor_id, visitor_name
FROM visitors
INNER JOIN users USING (visitor_id)";
[/code]


That produced the following error

Notice: Undefined variable: visitor_name in /home/sites/broadwaymediadesigns.co.uk/public_html/sites/the-tax-elephants/userinfo.php on line 93

Line 93 is below

[code=php]
echo "<strong>Name:</strong> ".$visitor_name['visitor_name']."<br>";
[/code]


So I put the following in just after the database connection

[code=php]
$visitor_name = mysqli_real_escape_string($db, $_POST['visitor_name']);
[/code]


but that produces the errors below

Notice: Undefined index: visitor_name in /home/sites/broadwaymediadesigns.co.uk/public_html/sites/the-tax-elephants/userinfo.php on line 37

Notice: Uninitialized string offset: 0 in /home/sites/broadwaymediadesigns.co.uk/public_html/sites/the-tax-elephants/userinfo.php on line 95
Copy linkTweet thisAlerts:
@ianhaneyauthorJun 28.2015 — I sorted the undefined index error by using the following code

[code=php]
$visitor_name = '';
if(isset($_POST['visitor_name'])){ $visitor_name = $_POST['visitor_name']; }
[/code]


Just unsure how to fix the Notice: Uninitialized string offset: 0 error

I googled it and is saying cause it is a string and not a array so unsure on this one, sorry
Copy linkTweet thisAlerts:
@ianhaneyauthorJun 28.2015 — UPDATE:

I now have the following

[code=php]
<?php
$db = mysqli_connect("" , "", "") or die("Check connection parameters!");
// Optionally skip select_db and use: mysqli_connect(host,user,pass,dbname)

mysqli_select_db($db,"") or die(mysqli_error($db));

if (mysqli_connect_error()) {
die ('Failed to connect to MySQL');
} else {
/*SUCCESS MSG*/
echo '';
}

$visitor_name = '';
if(isset($_POST['visitor_name'])){ $visitor_name = $_POST['visitor_name']; }

$sqlCommand3 = "SELECT visitor_id, visitor_name
FROM visitors
INNER JOIN users USING (visitor_id)";

$query = mysqli_query($db, $sqlCommand3) or die (mysqli_error($db));

$visitor_name=0;

//fetch the data from the database
while ($row = mysqli_fetch_array($query)) {

if ($row['visitor_id'] != $visitor_name) {

if ($visitor_name != 0) {

$visitor_name = $row['visitor_name'];

}
}
}

?>

<?php
$title = "My Account - The Tax Elephants";

$pgDesc="";

$pgKeywords="";

include ( 'includes/header.php' );
?>
<!--CONTENT-->

<div id="column-whole">

<?php
/* Requested Username error checking */
$req_user = trim($_GET['user']);
if(!$req_user || strlen($req_user) == 0 ||
!preg_match("/^[a-z0-9]([0-9a-z_-s])+$/i", $req_user) ||
!$database->usernameTaken($req_user)){
die("Username not registered");
}

/* Logged in user viewing own account */
if(strcmp($session->username,$req_user) == 0){
echo "<h1>My Account</h1>";
}
/* Visitor not viewing own account */
else{
echo "<h1>User Info</h1>";
}
/* Display requested user information - add/delete as applicable */
$req_user_info = $database->getUserInfo($req_user);
/* Username */
echo "<b>Username: ".$req_user_info['username']."</b><br>";

/* Email */
echo "<b>Email:</b> ".$req_user_info['email']."<br>";

echo "<strong>Name:</strong> ".$visitor_name['visitor_name']."<br>";

/**
* Note: when you add your own fields to the users table
* to hold more information, like homepage, location, etc.
* they can be easily accessed by the user info array.
*
* $session->user_info['location']; (for logged in users)
*
* $req_user_info['location']; (for any user)
*/
/* If logged in user viewing own account, give link to edit */
if(strcmp($session->username,$req_user) == 0){
echo '<br><a href="useredit.php">Edit Account Information</a><br>';
}
/* Link back to main */
echo "<br><a href='process.php'>Logout</a><br>";
?>

</div>

<?php
// Free the results

mysqli_free_result($query);

//close the connection
mysqli_close($db);
?>
[/code]


I got no errors but it is not displaying the full name from the visitors table?
Copy linkTweet thisAlerts:
@NogDogJun 28.2015 — I think we (and you? ? ) may need some clarification on exactly what the logic is you're trying to implement here. For instance, note this section (which I've reformatted the indenting but not changed the actual coding):
[code=php]
$visitor_name = 0; // <------<<< NOTE THIS

//fetch the data from the database
while($row = mysqli_fetch_array($query))
{
if($row['visitor_id'] != $visitor_name)
{
if($visitor_name != 0) // <-----<<< WILL NEVER PASS
{
$visitor_name = $row['visitor_name'];
}
}
}
[/code]
Copy linkTweet thisAlerts:
@ianhaneyauthorJun 28.2015 — I am trying to get data from one table and data from another table as on the userinfo.php page, I would like that page to display all the data and not just the username and email address from the users table

I would like the name to display as well that is stored in the visitors table so I need to match the id of the users table to that of the visitors table so they match up and displays the name of the username of the users table

cause if it don't match up, it could display a username but then someone else's name

I have noticed though the userid in the users table changes on login, for example I am logged in and it is one lot of letters and numbers and then if I logout and then login again, it displays completely different lot of letters and numbers

it seems like it generates a random mix of letters and numbers when logging in

hope that makes sense
Copy linkTweet thisAlerts:
@NogDogJun 29.2015 — But how do you know which row to pull from the tables -- i.e., where is your WHERE clause in the query?
Copy linkTweet thisAlerts:
@ianhaneyauthorJun 29.2015 — Sorry just a update

I have managed to do it with the following code on profile.php


[code=php]
$sql = "SELECT * FROM users INNER JOIN visitors on visitors.visitor_id = visitors.visitor_id WHERE users.id = $id LIMIT 1";
[/code]
×

Success!

Help @ianhaney spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...