So I have the code below (and at the top the database connector and session start). However, he doesn't echo the amount of cubes (a valuta on my site).
$cubes = mysql_query("SELECT cubes FROM leden WHERE id='" . $_SESSION['id'] . "'");
echo "You currently have " . $cubes;
What is going wrong here? The database is there, the tables and everything exist.
The mysql_query function returns you a result set. So if you want to get the information you must also do :
$cubesRow = mysql_fetch_object($cubes);
echo "You currently have " . $cubesRow->cubes;
Related
I've been searching for a couple of hours trying to figure this out:
person types his username in a text field and hits submit, then php checks if the username is in the database(in the table username). What method do i use? or what statement. Because this is really confusing me.
my database is named arcforum table is named afusers the rows are filled with usernames and what not.
Visual reference:
I tried using:
SELECT username FROM afusers WHERE username LIKE 'DarkEyeDragon';
But this returns nothing.
PS: I'm not asking for the completely filled in code(although always welcome). Just a method I can use to do this. Or a simular question.
Thanks in advance.
EDIT: http://i.imgur.com/4V0Cay1.png Proof table/database is not empty
Code:
include_once 'psl-config.php';
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
header("Location: ../error.php?err=Unable to connect to MySQL");
exit();
}
The next part just prints out every row in the table. Just to make sure everything is working as intended.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. "| Name: " . $row["username"]. "<br>email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
exit();
after that i'm not entirly sure how I would utilise the code to check if the words are the same.
$mysqli->query('select * from afusers where username = someusername')
You can verify the row quantity with $mysqli->num_rows
And then you can fetch your data like this:
$user = mysqli_fetch_object($mysqli)
That will give you the desired user if the username is unique.
Of course you could use a variable for the username like:
$mysqli->query('select * from afusers where username ="' . $username . '"')
I recently converted a code block into a function so I can call it easily more than just once. My problem is that as soon as I related the block to a function it fails the SQL query every time. Here's my code block:
function checkEvent()
{
if(!empty($_GET['e']))
{
$sql = mysqli_query($link, "SELECT * FROM events WHERE EventID = '" . mysqli_real_escape_string($link, $_GET['e']) . "'");
if($sql && mysqli_num_rows($sql)==1)
{
if($row = mysqli_fetch_row($sql))
{
$eventid = $row[0];
$eventname = $row[1];
$desc = $row[2];
$time = $row[3];
echo $_GET['e'];
}
}
else
{
echo $sql;
$failure = "Num Rows Error encountered: " . mysqli_error($link) . " / Num Rows: " . mysqli_num_rows($sqlE);
}
}
}
Now, I've added echos in the relevant places to check and where it currently says echo $sql; if I change that to echo "Fail."; then it will indeed do that. I have tried to get the result as a number of rows and that comes back blank. I don't understand this as my EventID is an AUTO INCREMENT and as such HAD to start at 1. I've triple checked the first entry is 1 as well.
I'm probably not seeing something really obvious, I just can't understand why this code block stopped working the instant I placed a function block around it.
$link doesn't exist inside your function. You either need to pass that as a parameter to the function or skip it entirely and use the "current" DB connection.
"current" in quotes because while it should work just fine while you're utilising a single database connection for the entire process, as soon as you'd start using multiple connections (to connect to multiple databases,) this approach would fail terribly.
Basically I've connected my PHP to the mysql database which loads a bunch of users names. I want to be able to click on any of the users name so I've hyperlinked them all through a while loop and . When I click one of the links it opens a new page but I would like to be able to tell which username I clicked on. I think I could do this by using $_GET but I'm getting the following errors:
<?php echo "$first" . " " . "$last";?>;
Also, what should I write in the new page? So far on the new page this is what I've wrote:
$first=$row['FName'];
$last=$row['LName'];
echo "USERNAME: " . "$first";
UPDATE:
echo "<tr>
<td><b><center>.$info['Name']."</td></center></b>
</tr>";
This also gives error, but I think it shouldn't? Maybe I've made a simple mistake with the " somewhere, please check if you can find
In your new page you would check $_GET variable to see if the keys are set.
You have link with usersProfile.php?firstname=somename&lastname=somelastname so the keys you are looking for are firstname and lastname.
You would have to check if the key is set in order to avoid getting undefined indexes.
Ex. $firstname = isset($_GET['firstname']) ? $_GET['fisrtname'] : null;
This checks if the key is set and if it is sets $firstname to the data from the url otherwise to null
If I understand your question correctly, it appears that you are trying to create a link for each user that will send you to a different or personal page when clicked.
In that case, it might be easier to simply query the entire table and have that set up in your html page as a separate .
For instance:
//Database connections
$query="SELECT * FROM userTable WHERE firstName = $firstname and lastName = $lastName";
//Change the query to whatever you want
$result = mysql_query($query)
while($row = mysql_fetch_assoc($result))
{
echo "<a href='somepage.php'>" . $row['Username'] . "</a>";
}
This is just an example and a good amount would need to be added to it, but this more than likely would be easier for what you are trying to do. In this case, the loop would output all the names you have pulled from the database.
I get a list of records and each record is a question / answer / timestamp.
I created a basic PHP report:
<?php
$con = mysql_connect("localhost", "login", "pass");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query(" SELECT *
FROM `experiment`
where userid = 73");
while ($row = mysql_fetch_array($result)) {
echo "question " . $row['question'] . "answer " . $row['answer'] .
"time " . $row['time'] . "stamp " . $row['createdAt'] . "<br>";
}
I need some way to compare the row in front of createdAt and the row after createdAt.
If the difference between two rows is bigger then 2 minutes, the thing should echo "warning".
I'll assume a couple of things on your behalf. This may change the value of the answer, but you simply haven't provided the necessary information for an answer to be feasible at this point.
I am going to assume that you are looping through the data records. You imply this by stating that there is a display of multiple rows. Your SQL query only gets the data of one row. I'll assume that you actually have gotten an entire record set instead. Because otherwise, the data structure needs to be examined for its design choices. I am also making an assumption on how userid is used in a table, mind, so that's my personal bias.
As record sets are collected, they can be manipulated. You're using the ancient mysql_* method here. I recommend that you read the PDO methodology that php has available at 5.2.7+ and consider upgrading your php version if you don't already have it.
The manipulation can take many forms.
$previousRecord = 0;
foreach ($recordSet as $index=>$record){
$recordSet[$index]['warningTime'] = FALSE;
if ($previousRecord){
if (($record['createdAt']-$previousRecord) > 120){
$recordSet[$index]['warningTime'] = TRUE;
}
}
$previousRecord = $record['createdAt'];
// Other data manipulation logic for page presentation
}
This should inject the warning right into the dataset that can be displayed whenever you want it to be. I do prefer a seperation of functions for maintainability; calling the database, extracting/formatting the data, displaying the data. It makes future changes much easier, also allows for code portability. You do not have this in your code, which means that whenever you do something like this again, well, you'll re-invent the wheel.
$createdAt = null;
while($row = mysql_fetch_array($result)) :
// initialise on first run
if ($createdAt === null) :
$createdAt = $row['createdAt'];
endif;
// now $createdAt is the value of the last row... if so, echo warning, else echo nothing
echo checkCreatedIsOlderThanTwoMinutes($createdAt, $row['createdAt']) === true ? "WARNING!" : "";
echo "question ". $row['question']. "answer ". $row['answer']. "time ".$row['time']."stamp ". $row['createdAt']."<br>";
endwhile;
I don't have a clue what the format of your createdAt looks like, so I use this pseudo-function:
function checkCreatedIsOlderThanTwoMinutes($oldCreatedAt, $newCreatedAd)
{
// check that stuff
}
Hope that helps.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to count the site current visitors using java script or php
I have an embedded stream on my website, but I want to pull the number of live viewers on the page. Is there a way to do this with PHP / AJAX, show the number of people currently viewing one of my webpages?
DISCLAIMER: I did something like this a LONG time ago, so here is the ugly old code (That I'm not going to put effort into making look nicer / not when I first started programming as this is just to give you an idea of how it can be done, and not to spoon feed any specific code).
$timeout = time() - (20);
$sessid_exist = mysql_query("SELECT sessid FROM bw_sessions WHERE sessid='" . session_id() . "'") or die (mysql_error());
$sessid_check = mysql_num_rows($sessid_exist);
if ($_SESSION['bw_username']) {
$sql = mysql_query("UPDATE bw_sessions SET timestamp='" . time() . "', username='" . $_SESSION['bw_username'] . "' WHERE sessid='" . session_id() . "'");
} else {
if($sessid_check > 0){
$sql = mysql_query("UPDATE bw_sessions SET timestamp='" . time() . "' WHERE sessid='" . session_id() . "'");
} else {
$sql = mysql_query("INSERT INTO bw_sessions (id, username, sessid, timestamp, ip)
VALUES(null, '', '" . session_id() . "', '" . time() . "', '" . $_SERVER['REMOTE_ADDR'] . "')") or die (mysql_error());
}
}
$sql = mysql_query("SELECT distinct sessid FROM bw_sessions WHERE username='' AND timestamp >= '$timeout' ORDER BY timestamp DESC") or die (mysql_error());
$sql2 = mysql_query("SELECT distinct sessid,username FROM bw_sessions WHERE username!='' AND timestamp >= '$timeout' ORDER BY username DESC") or die (mysql_error());
$num_guests = mysql_num_rows($sql);
$num_reg = mysql_num_rows($sql2);
?>
<font size='1'>Currently Online: <br>
<?=$num_guests;?> Guests<br>
<?=$num_reg;?> Registered users
You just need to make a table and hold session_id's.. then query that table for any "recent" activity. If you want real time updates, put code above (modified to your table design) in "online.php" and call it via jquery every x seconds, or however you decide to do it.
Something like Clicky should work for you.
If you've seen it somewhere, it probably IS possible, and this sort of thing is built into most forum sofware, and it's used on a lot of websites, so it's probably not that hard.
The usual way of doing this gets the IP of a connected visitor from $_SERVER['REMOTE_ADDR'] and then writes that to a file, and adding up all the unique IP's to find out how many people are connected.
This will need some sort of cleaning function to remove any IP's that are no longer connected.
The script runs on pageload, and counts visitors in a file, so if using ajax you run a PHP script polling that file every so often to update the count dynamically, or you could do it on pageload, but then ajax is'nt necessary as you could just do it with PHP.
If you don't already know how, figuring out how to run a PHP script in $.ajax is the first thing to do, then writing a function that counts visitors is probably the next.
I got 244 million hits on a search for such a script, and there's one here and here.