As soon as i added .$thedatabase->displayavatar($username1,2). nothing is being displayed. It isn't a jQuery problem, so i haven't included that code. Why is it when i add that code nothing is returned with json_encode?
leaderboard.php
$thedatabase = new Database();
$thedatabase->opendb();
while($row = mysql_fetch_assoc($getleader)) {
$username1 = $row['username'];
$rating = $row['rating'];
$username = str_replace(' ','-',$username1);
$leaderboard[] = "<div class='leaderboard-user'><ul><li>".$thedatabase->displayavatar($username1,2)."</li><li><a>$username1</a></li><li>$rating</li></ul></div>";
}
$thedatabase->closedb();
echo json_encode($leaderboard);
displayavatar function in Database class
echo "<a href='/user/$user'><img src='/test.png' width='70px' height='70px' /></a>";
You're fetching the row
$username1 = $row['username'];
$rating = $row['rating'];
$username = str_replace(' ','-',$username1);
so your username is in $username, but for the funcion
$thedatabase->displayavatar($username1,2)
you are using the $username1, there's propably the empty char, and it can't make query
if it's not relevant for your query and there can be empty char, then sorry :))
Related
I am trying to setup $_SESSION data and echo it out onto the page. I am defining the sessions in the header
<?php
$users = $mysqli->query('SELECT * FROM fn WHERE username = '.$_SESSION['username']);
if (is_object($users)) {
if ($users->num_rows) {
while ($row = $users->fetch_assoc()) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$email = $row['email'];
$number = $row['number'];
$region = $row['region'];
$company = $row['company'];
$level = $row['level'];
}
}
}
$_SESSION['first_name'] = $first_name;
?>
I am then including the header.php file on my page and also using session_start();
I have no idea what im doing wrong.
I am managing to get the username and password to echo out... I assume its because it was added to the session upon login.
session_start() must come before you attempt to use $_SESSION variable, not after. Move your included file which contains session_start() to the top of that file for this to work.
You need to add session_start(). Put it after your PHP start tag
I'm sorry if this has been asked, but I have no idea what to search for to find an answer.
I'm just starting to learn PHP and am doing a simple tutorial where I'm "logging into" a data base (just checking to see if the email and password match what is stored no actual session is being created).
I have this code:
<?php
include("connectToDb.php");
$loginEmail = $_POST['loginEmail'];
$loginPassword = $_POST['loginPassword'];
$query = mysqli_query($dbc, "SELECT * FROM users WHERE email='$loginEmail'");
$numrows = mysqli_num_rows($query);
if($numrows != 0)
{
while($row = mysqli_fetch_array($query))
{
$dbemail = $row['email'];
$dbpassword = $row['password'];
$dbfirstname = $row['firstName'];
}
if($loginEmail == $dbemail)
{
if ($loginPassword == $dbpassword)
{
echo "Hi ".$row['firstName'].", you are now logged in.";
}
else
{
echo "login failed.";
}
}
}
mysqli_close($dbc);
?>
But the $row['firstName'] in the echo statement prints as a blank string: "Hi , you are now logged in.". If I use the exact same code but repalce $row['firstName'] with $dbfirstname in the echo statement, I get a properly formatted message "Hi Jason, you are now logged in.".
Those two variables are supposed to be the same... why does one work while the other does not?
Check the control flow:
You have the while loop while($row = mysqli_fetch_array($query)) - so you assign a new value to $row and test it. If it evaluates to false (i.e. no more rows), you break the loop.
This implies, that after the loop $row no longer has valid content. Your stored values (e.g. $dbfirstname) are from the previous iteration of the loop and thus contain valid data.
So i ran into some trouble not to long ago. As a student i am relativly new to programming and thus i often visit sites like these for help. My question is how can i add value to database by pressing a button. For me the problem here is that the button has a javavscript function to print. So in other words i want the button to have 2 functions, one that prints the page (which i already have) and one that adds value to the database. The purpose to adding the value to database is so people can see that its already been printed before.
So essentialy what i am asking for is how can i give a button 2 functions (one which is Javascript) and show people that the button is used(in this case, that it has been printed). All help will be appreciated very much.
My code is as following:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='window.print()' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
This would aquire 2 tasks:
Is that you bind a function to the click handler of the button.
Although it is bad practice to use function calls directly, in your case this would be that you replace the window.print() by a custom javascript function.
In that javascript function, you execute the window.print() again, where-after you do the next step in the logic: sending data to PHP.
With ajax you can archieve this.
With a parameter in the function you can pass what the ID of the current row is, which need to be passed to PHP.
You need to create another PHP script, that will be called by tje AJAX script.
In that PHP script you will do the required updates to the database.
Ok There is a lot of ways you can do it but here is how i would do it :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
//first you call a custom javascript function after the 'onclick'. I believe you'll have to pass a variable as an argument (like $id).
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
Then you write this function in the header of your page
<script>
function print_table(id)
{
//print your document
window.print();
//send your data
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://www.domaine.com/directories/printed_table.php?id=" + id;
xmlhttp.send();
}
</script>
Then you write your file printed_table.php where you store 1 if printed or 0 if not printed. I don't understand german so i don't know where you store your printed variable but it goes like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1 WHERE `id` = `$id`");
?>
This should work. Just be careful and check the $_GET['id'] before to use it for security purposes. like you can use the php function is_int(). Depending of the security level you need you might want to secure this code a little more.
I'm working on a filter in which results are filtered right away, I'm wondering if that may be the cause of the problem so I thought I would ask and see if anyone could give me a pointer on how to proceed.
<script>
var services = [
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$url = $row["$url"];
$title = $row["$title"];
$amount = $row["$amount"];
$id = $row["$id"];
$status = $row["$status"];
$nonprofit = $row["$nonprofit"];
echo '{"permalink": "';
echo "{$url}";
echo '",';
echo '"title": "';
echo "{$title}";
echo '",';
echo '"amount":';
echo "{$amount}";
echo ',';
echo '"id": "';
echo "{$id}";
echo '",';
echo '"status": "';
echo "{$status}";
echo '",';
echo '"address": "';
echo "{$address}";
echo '",';
echo '},';
}
}
?>
]
//]]>
</script>
<script id="template" type="text/html">
<a title="{{title}}" href="{{permalink}}">
<div class="fs_box hide-for-small-down">
<div class="fs_left">
<span class="fs_head">{{title}}</span>
<span class="fs_id"><img src="images/{{id}}.jpg" width="75%" height="75%" onError="this.onerror=null;this.src='images/logo.png';"></span>
<span class="fs_status">{{status}}</span>
<span class="fs_disc">{{address}}</span>
</div>
<div class="fs_price">${{amount}}+</div>
<div class="clear"></div>
</div>
</a>
</script>
I'm expecting it to produce a bunch of results that then are filtered criteria which are elsewhere in the page.
When I try it currently just as a php code it outputs fine. However, when I try it in the php file that this should go in it produces nothing. Or does it dislike being in a script?
Thanks for any help!
You can use json_decode and json_encode to turn an array to json and json back to an array.
Also someone will probably mention that you should not be using the mysql_* functions in PHP as they are depreciated.
Something like this:
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
$results = array()
while($row = mysql_fetch_array($result)) {
$results[] = $row;
}
$json = json_encode($results);
}
?>
]
<script>
var services = <?php echo $json; ?>;
</script>
This would give you a json object to use to render in your script.
What extension is the file you are saving?
If it's not .php or an extension set to render php, then you'll just have the code show up as test.
You might want to pull out the "die" statement after the db connect. This looks like you are running php in a .js file so you probably want the entire file to write out rather than stop because you couldn't connect to the database (or at least give 0 results, maybe a warning)
I am creating a login based application and this is what I have so far. I am trying to read each field into a separate textarea. I have tried to bind the data etc. I do get a output in the textarea, but it prints all the fields in one textarea. Please help.
<?php
selectDB();
function selectDB() {
$usertoken = $_POST['usertoken'];
//Database service vars
$databasehost = "localhost";
$databasename = "morerandom";
$databasetable = "random";
$databaseusername = "root";
$databasepassword = "root";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT username, useremail, firstname, lastname FROM $databasetable WHERE usertoken='$usertoken'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count)
{
$rows = array();
while ($row = mysql_fetch_object($result)) {
$rows[] = $row;
}
echo $rows[0]->username . "\n";
echo "\n";
echo $rows[0]->useremail . "\n";
echo $rows[0]->firstname . "\n";
$first = $rows[0]->lastname;
echo $first;
// echo "$lastname;"
}
else
{
echo 'Token not valid';
}
mysql_free_result($result);
mysql_close($con);
}
?>
What you are getting is just one string. There are better way to retrieve this kind of data from the server side(XML or AMF).
If you want to go ahead with your method then split the string using '\n' as a delimiter but check first that the server response is not 'Token not valid'.
So something like this should work:
First remove the echo "\n"; line under the echo $rows[0]->username . "\n";
var responseArray:Array = theStringResult.split('\n');
So now the responseArray stores the username at position 0, useremail at position 1, firstname at position 2 and lastname at position 3.
But again, you are sending data from the server as raw text and this is not the best way to do it. Check this link to see how this can be done using AMFPHP.