i created a script that connects to my database called mysqlconnecter:
<?php
define("DB_USERNAME", "root");
define("DB_PASSWORD", "pass");
define("DB_DATABASE", "adventure_of_dragons");
define("DB_SERVER", "127.0.0.1");
$db_handle = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$db_found = mysql_select_db(DB_DATABASE, $db_handle);
if ($db_found || true) {
$SQL = "SELECT * FROM members";
$result = mysql_query($SQL) or die(mysql_error());
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
}
mysql_close($db_handle);
} else {
echo "Database NOT Found " . $db_handle;
}
?>
And then I created another script that includes mysqlconnecter.php and posts the data inside the database:
<?php
include "mysqlconnecter.php";
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
// two <br>'s, so we get an empty line between users
?>
but the output displays the data inside the database twice:
ID = 4
RANK = 100
USERNAME = user
PASSWORD = password
ID = 4
RANK = 100
USERNAME = user
PASSWORD = password
I only want it displaying the text once,
What do I do?
Your logic is slightly the wrong way round.
This is because your loop is finished then you are echoing the data so it will always be the last row.
You need to echo whilst in the loop or create an array then loop the array later.
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
//this will echo for EVERY row the loop iterates.
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
}
For your double output i suspect you have included the file twice. But thats guessing as i don't see all of your code.
If you want to keep the display code outside your mysqlconnecter.php file, you could do this in your loop:
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = array(
'id' => $row['member_id'];
'username' => $row['username'];
'password' => $row['password'];
'rank' => $row['rank'];
}
And then in your script:
include "mysqlconnecter.php";
foreach ($data as $key => $value)
{
echo 'ID = ' . $value['id'] . '<br>';
// etc
}
For your "double print" problem, I would try to put a var_dump($data); right after your while() in mysqlconnecter.php, to see what happens exactly.
If the var_dump display correctly reflects the expected result of your query, the problem is elsewhere, possibly that you include mysqlconnecter.php twice, as Dave suggested. To be sure it's included only once throughout your whole code, simply replace include() with include_once().
Are you sure you don't have any mistake? is that all code you show us?
Because logically your script will print once and will print the last data from your members table
I have try it
Related
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.
This is my code and I am unable to run my simple condition. I have used all the ways but it's not working. As I wanted that if count is available then show count and if not then echo 0 in . I know it is simple but I am stuck on it.
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "usman";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$result = $dbh->query(
"SELECT COUNT(*) as cnt
FROM ams
where empid= {$_SESSION['sess_user_id']}
GROUP BY leavetype
HAVING leavetype = 'Annual'"
);
if (!$result) {
echo "<td>";
echo 0;
echo "</td>";
} else {
foreach ($result as $row) {
echo "<td>" . $row['cnt'] . "</td>";
echo "<br>";
}
}
?>
Your solution
<?php
session_start();
$hostname = "localhost";
$username = "root";
$password = "";
$db = "usman";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$result = $dbh->query("SELECT COUNT(*) as cnt FROM ams where empid= {$_SESSION['sess_user_id']} GROUP BY leavetype HAVING leavetype = 'Annual'");
if (!$result) {
echo "<td>" . 0 . "</td>";
} else {
foreach($result as $row) {
echo "<td>" . $row['cnt'] . "</td>";
echo "<br>";
}
}
?>
Explanation
It appears you are missing a } at the end of your if-else loop. Additionally, if you are using $_SESSION super-global variables, you need to invoke session_start() first.
Note: While using if else conditions from the Query it is advisable to echo the Query and exit the operations after that line so that we can see the query that we have to execute in the browser and you can navigate to phpmyadmin and place the query in SQL and click on GO. So that this is one of the very easy method to find whether the query runs or not.
Missing Condions:
Session Start is missing in the file
Close brace for the loops opened is missing
General Instruction:
Sometimes if the query is not executing properly also the result of the query will return FALSE so that it is adviced to take the count of the rows after tht query is executed and perform the operations after that.
Your Correct Code look like:
<?php
session_start();
$hostname = "localhost";
$username = "root";
$password = "";
$db = "usman";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$result = $dbh->query("SELECT COUNT(*) as cnt FROM ams where empid='".$_SESSION['sess_user_id']."' GROUP BY leavetype HAVING leavetype = 'Annual'");
$count = $result->num_rows;
if($count==0)
{
echo "<td>" . 0 . "</td>";
}
else {
foreach($result as $row) {
echo "<td>" . $row['cnt'] . "</td>";
echo "<br>";
}
}
?>
If you check the condition with the count of the query executed you can attain your solution in a better way and you can understand very easy so that it avoids confusion if you look at the code some years back too.
I'm creating a search bar feature on my website where the user can search for users using a name.The search result may come up with multiple users with similar names (ex. if I search "Jenna", my database may have multiple users with the name "Jenna" so multiple results will show).I want the user to be able to click on one of the profiles and see that specific "Jenna's" user profile. Kind of like Twitter, where I can search for accounts and view different profiles. Right now I have code that returns the search and also makes the search result a clickable link. However, when I try to save the user id, it only saves the latest user id.
home.php (where the search bar for users is0
<form method="GET" action="search.php" id="searchform">
Search for users:
<input type="text" name="search_user" placeholder="Enter username">
<input type="submit" name="submit" value="Search">
</form>
search.php (prints out the users with the name that the user is searching for)
session_start();
$user = '';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$search_user = $_GET['search_user'];
$sql = "SELECT * FROM users WHERE username LIKE '%$search_user%'";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a';
$b = ' href="';
$c = 'user_profiles.php';
$d = '">';
$e = $row['username'];
$f = '</a';
$g = '>';
$_SESSION['user'] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a.$b.$c.$d.$e.$f.$g;
header("Location: user_profiles.php");
}
}
user_profiles.php (supposed to be where a specific user's profile is shown, based on the link the user clicks with the specific userID)
session_start();
$userID=$_SESSION['user'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '</div>';
}
I get where my mistake is, the while loop in search.php will only save the latest userID so the link will always take me to the user profile with that useriD. I'm just not sure how to implement it so that when the user views the list of profiles, the link they click will take them to a specific profile based on the user id.
You need to do changes in search and user.php files :
Search.php :
<?php
session_start();
$user = '';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link, "GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$search_user = $_GET['search_user'];
$sql = "SELECT * FROM users WHERE username LIKE '%$search_user%'";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
?>
<a href="user_profiles.php?id=<?php echo $id; ?>" >
<?php echo $row['username']; ?>
</a>
<?php
$_SESSION['user'] = $row['user_id'];
$userID = $_SESSION['user'];
header("Location: user_profiles.php");
}
}
User_profile.php:
$userid = $_GET['id'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query = "SELECT * FROM dataTable WHERE user_id='$userid'";
$results = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output = $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . "<br>" . "<br>";
$output = $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . " hrs" . "<br>" . "<br>";
$output = $row["date_"];
echo "Date: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . "<br>" . "<br>";
echo '</div>';
}
Very first thing, you are saving multiple user ids to a string.
Another thing, you are saving it in while loop.
Therefore, latest value updates old value.
In your case, it will always save the last value. That is prime issue.
You can take array of user ids and save them in it.
$userIds = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a';
$b = ' href="';
$c = 'user_profiles.php';
$d = '">';
$e = $row['username'];
$f = '</a';
$g = '>';
$userIds[] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a.$b.$c.$d.$e.$f.$g;
header("Location: user_profiles.php");
}
$_SESSION['user'] = $userIds;
And in your user_profiles.php, loop over the array or use MySQL IN() condition to get all user profiles.
Also, why did you take too many variables for html link. You can do it in single variable using concatenation like following:
$userIds = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a'
. ' href="';
. 'user_profiles.php';
. '">';
. $row['username'];
. '</a';
. '>';
$userIds[] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a;
header("Location: user_profiles.php");
}
$_SESSION['user'] = $userIds;
Another mistake is that you are echo ing HTML link and doing redirection.
That will cause headers already sent... error.
This will display list of users with searched string
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)) {
$link="<a href='user_profiles.php?user_id=".$row['user_id']."'>".$row['username']."</a>";
}
}
After clicking on link it will redirect to user_profiles.php (no need to header. header is used for automatic redirection)
In user_profiles.php
session_start();
$userID=$_GET['user_id'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '</div>';
}
The code below works fine. However I would like to output the results using a loop. I can do it by going through each key individually or as $post[0] for example but not using a loop to go through all the returned fields. All I get is one value of "Array". It looks like the entire array is inserted into a variable I'm not sure what's going on. I have tried http://www.hackingwithphp.com/5/3/0/the-two-ways-of-iterating-through-arrays. Any suggestions appreciated and also if anyone could explain what is going on that would be great. Thanks.
$ID = $_POST['ID'];
function query($ID){
$servername = "x.x.x.x";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM GROUP WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
$resArr[] = $row;
}
return $resArr;
}
$person = query($ID);
foreach($person as $post) {
echo $post['ID'] . "<br>";
echo $post['NAME'] . "<br>";
echo $post['POSITION'] . "<br>";
echo $post['TELEPHONE_NUMBER'] . "<br>";
echo $post['EMAIL'] . "<br>";
}
?>
Its not totally clear what you are asking but I assume you want to loop through the individual fields of the selected rows. As you built an array containing the query results each result itself being an array mysqli_fetch_array($result) then you can just add an inner loop to process the individual row array like so :-
$persons = query($ID);
foreach($persons as $person) {
foreach ( $person as $fieldname => $value ) {
echo $fieldname . '-' . $value . "<br>";
}
}
Group is reserved word of mysql you can use it in backtics ``
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM `GROUP` WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);
I am trying to retrieve information from my database depending on the ID a user types into my URL.
For example: If USER A went to www.exampleurl.com/index.php?id=1 it would echo out the user's information which has an ID of 1. Same thing if the id was 2, 3, etc. Users are entering their information via a form in a different file called submit.php.
Here is my code to retrieve data depending on ID :
<?php
$id = $_GET['id'];
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
echo "Hello, " . $result['name'];
?>
Any ideas on if my SELECT request is wrong?
EDIT
Here is my code for showing the data altogether in a table. This works fine.
<?php
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "!";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query, $con);
echo "<table border=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Age </th>
</tr>";
while($record = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['name'] . "</td>";
echo "<td>" . $record['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
→ Try This:
You should consider using PHP PDO as it is safer and a more object oriented approach:
$usertable = "";
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME', 'DB_USER_NAME', 'DB_USER_PASS' );
$statement = $database->prepare('SELECT * FROM $usertable');
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<tr>";
echo "<td>" . $R[ $x ]['id'] . "</td>";
echo "<td>" . $R[ $x ]['name'] . "</td>";
echo "<td>" . $R[ $x ]['age'] . "</td>";
echo "</tr>";
}
}
else { echo "Error!"; }
you need to use mysql_fetch_assoc function for retrieve the results.
$result = mysql_fetch_assoc(mysql_query($query, $con));
echo "Hello, " . $result['name'];
You should be error checking your mysql_querys:
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
if(!result)
echo mysql_error();
You should also retrieve the results:
$array = mysql_fetch_assoc($result);
I'll consider some secure features like
Check if $_GET['id'] is set and if is int
Apply Mysql escape with mysql_escape_string() function