I have been trying to get the names of users from the database using jQuery and php but I've had no luck so far. It manages to post value in the text field to the name.php file but i can't echo out the names linked with the username in the database.
The HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Retail Management Application</title>
</head>
<body>
Name: <input type="text" id="username">
<input type="submit" id="username-submit" value="Grab">
<div id="username-data"></div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
The global.js file:
$('input#username-submit').on('click', function() {
var username = $('input#username').val();
if ($.trim(username) != '') {
$.post('ajax/name.php', {username: username}, function(data){
$('div#username-data').text(data);
});
};
});
name.php:
<?php
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
require '../db/connect.php';
$query = mysqli_query("
SELECT `username`.`name`
FROM `users`
WHERE `users` . `username` ='". mysqli_real_escape_string(trim($_POST['username'])). "'
");
/* $query = DB::getInstance()->query("SELECT `username`.`name` FROM users
WHERE `users` . `username`
= '". mysqli_real_escape_string(trim($_POST['username']))."'"); */
echo (mysqli_num_rows($query) !== 0) ? mysql_result($query, 0, 'name') : 'Name not found!';
//tenary operator.
}
?>
connect.php:
<?php
$con = mysqli_connect("localhost","root","root")
or die("Error " . mysqli_error($con));
mysqli_select_db("retail_management_db");
?>
You must use mysqli_fetch_array to get the result and then echo it.
Put this under your mysql query
if($query)
{
while($query_result = mysqli_fetch_array($query))
{
//This returns an array of the fetched values
$name = $query_result['name'];
}
echo $name;
}
else
{
echo "Query Failed";
}
Name.php then becomes
<?php
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
require '../db/connect.php';
$query = mysqli_query("
SELECT `username`.`name`
FROM `users`
WHERE `users` . `username` ='". mysqli_real_escape_string(trim($_POST['username'])). "'
");
if($query)
{
while($query_result = mysqli_fetch_array($query))
{
//This returns an array of the fetched values
$name = $query_result['name'];
echo $name;
}
}
else
{
echo "Query Failed";
}
/* $query = DB::getInstance()->query("SELECT `username`.`name` FROM users
WHERE `users` . `username`
= '". mysqli_real_escape_string(trim($_POST['username']))."'"); */
//You should not use mysqli with mysql
echo (mysqli_num_rows($query) !== 0) ? mysql_result($query, 0, 'name') : 'Name not found!';
//tenary operator.
}
?>
Edited Area
Don't use Mysql functions with Mysqli
Your name.php now should be
<?php
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
require '../db/connect.php';
$query = mysqli_query("
SELECT `username`.`name`
FROM `users`
WHERE `users` . `username` ='". mysqli_real_escape_string(trim($_POST['username'])). "'
");
if($query)
{
//We check if the returned rows are at least one
if(mysqli_num_rows($query) > 0)
{
while($query_result = mysqli_fetch_array($query))
{
//This returns an array of the fetched values
$name = $query_result['name'];
echo $name;
}
}
else
{
echo mysqli_real_escape_string(trim($_POST['username'])) . "Name not Found";
}
}
else
{
echo "Query Failed";
}
/* $query = DB::getInstance()->query("SELECT `username`.`name` FROM users
WHERE `users` . `username`
= '". mysqli_real_escape_string(trim($_POST['username']))."'"); */
//You should not use **mysqli** with **mysql**
/*echo (**mysqli_num_rows**($query) !== 0) ? **mysql_result**($query, 0, 'name') : 'Name not found!';*/
//tenary operator.
}
?>
Edit
Use this temporarily as your html file Check if name.php actually echoes anything If it prints anything then the problem is from your js Make sure the action on the form is linked to the correct name.php file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Retail Management Application</title>
</head>
<body>
<form action = 'name.php' method = 'post'>
Name: <input type="text" id="username">
<input type="submit" id="username-submit" value="Grab">
</form>
<div id="username-data"></div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
Related
this is my login.php file
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name=$password="" ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = testInput($_POST["name"]);
$password = testInput($_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
//echo "Name ".$_POST["name"];
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")){
if($result->num_rows > 1){
echo "you are logged in";
while ($row = $result->fetch_assoc()){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
$result->close();
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
$conn->close();
?>
</body>
</html>
One problem is that my query
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")) returns column names as one row. I don not know whether it is ok ? The other thing whether I put wrong name or password or correct , in both cases I do not get any output. What I am doing wrong here ? And if you can please tell me how to write a mysqli query in php with correct format with a comprehensive example . I searched on google but there are different ways so I am confused specially when column names and variables come in the query.
Your test_input function is weak/unsafe, also, mysql_query is depricated, use mysqli and prepared statements as explained here: http://php.net/manual/en/mysqli.prepare.php
Furthermore, I included a section of code I use for my login system (bit more sophisticated using salts etc, you should be able to compile it in a piece of script suitable for you.
//get salt for username (also check if username exists)
$stmtfc = $mysqli->stmt_init();
$prep_login_quer = "SELECT salt,hash,lastlogin FROM users WHERE name=? LIMIT 1";
$stmtfc->prepare($prep_login_quer);
$stmtfc->bind_param("s", $username);
$stmtfc->execute() or die("prep_login_quer error: ".$mysqli->error);
$stmtfc->store_result();
if ($stmtfc->num_rows() == 1) {
$stmtfc->bind_result($salt,$hash,$lastlogin);
$stmtfc->fetch(); //get salt
$stmtfc->free_result();
$stmtfc->close();
I don't know what do you mean but thats how i query mysqli
$query = mysqli_query($db, "SELECT * FROM users WHERE name='$name' AND password='$password'");
if($query && mysqli_affected_rows($db) >= 1) { //If query was successfull and it has 1 or more than 1 result
echo 'Query Success!';
//and this is how i fetch rows
while($rows = mysqli_fetch_assoc($query)) {
echo $rows['name'] . '<br />' ;
}
} else {
echo 'Query Failed!';
}
i think thats what you mean
EDIT:
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name = null ;
$password= null ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = mysqli_real_escape_string($conn, $_POST["name"]); //I updated that because your variables are not safe
$password = mysqli_real_escape_string($conn, $_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='{$name}' and password='{$password}'")){
print "rows are ".mysqli_num_rows($result)"<br>";//number of rows
if($result && mysqli_affected_rows($conn) >= 1){//If query was successfull and it has 1 or more than 1 result
echo "you are logged in<br>";
while ($row = mysqli_fetch_assoc($result)){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
mysqli_free_result($result);
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
mysqli_close($conn);
?>
</body>
</html>
try to change this query
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")
to
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password' limit 1")
then you will get only one row , and try to change
$row = $result->fetch_assoc()
to
$row = $result->mysqli_fetch_row()
then you can display the results by colomn number instead of colomn name
<?php
mysql_connect("abc.com","user","password");
mysql_select_db("database name");
$query1="select * from table_name";
$exe1= mysql_query($query1);
$row= mysql_fetch_assoc($exe1);
if($row["email"]==$_POST["email"] && $row["[password"]==$_POST["password"]) {
echo "Login successfully";
} else {
echo "error in login";
}
?>
enter your column name in row["email"] and $row["password"]
I"m attempting to display some data I've sent from ajax to a php file, however for some reason its not displaying it on the page. The way it works it I enter a search term into a input field, and a ajax script post the value to a php script, which return the database value requested back.
error_reporting(E_ALL);
ini_set('display_errors', '1');
if (isset($_POST['name']) === true && empty($_POST['name']) === false) {
//require '../db/connect.php';
$con = mysqli_connect("localhost","root","root","retail_management_db");
$name = mysqli_real_escape_string($con,trim($_POST['name']));
$query = "SELECT `names`.`location` FROM `names` WHERE`names`.`name` = {$name}";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$loc = $row['location'];
echo $loc;
}//close While loop
} else {
echo $name . "Name not Found";
}
}
html form:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Retail Management Application</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id="name-submit" value="Grab">
<div id="name-data"></div>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
You're appending a MySQL error result to your query, and you're trying to query a query result, try the following:
$query = "SELECT `names`.`location` FROM `names` WHERE`names`.`name` = '$name'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
Edit:
{$name} that is a string and should be quoted instead.
change it to '$name' in the where clause.
Using:
$result = mysqli_query($con, $query) or die(mysqli_error($con));
will provide you with the reason as to why your query failed.
Im messing around, trying to see if i can make one of those clickable pet sites that were all the rage a couple years ago and i run into a problem with trying to use if, else, elseif stuff in PHP.
Heres what I have:
<?php
include_once "mysql_connect.php";
$newip = $_SERVER['REMOTE_ADDR'];
$oldip = mysql_query("SELECT lastip FROM sitefunctions WHERE name='index'");
if ($newip == $oldip) {
$message = "You were the last one to click this pet, please wait until someone else has clicked it before trying again.";
}
else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='index'");
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='index'");
$tempclicks = mysql_query("SELECT `clicks` FROM sitefunctions WHERE name='index'");
$message = "You gave this pet a click!";
};
if ($tempclicks == 150) {
mysql_query("UPDATE sitefunctions SET `level` = 2 WHERE name='index'");
$message = "Your click leveled the pet up!";
}
elseif ($tempclicks == 600) {
mysql_query("UPDATE sitefunctions SET `level` = 3 WHERE name='index'");
$message = "Your click leveled the pet up!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='index'");
while($row = mysql_fetch_array($sql)){
$clicks = $row["clicks"];
$level = $row["level"];
$name = $row["name"];
$image1 = $row["image1"];
$image2 = $row["image2"];
$image3 = $row["image3"];
};
if ($level == 1) {
$imageu = $image1;
}
elseif ($level == 2) {
$imageu = $image2;
}
elseif ($level == 3) {
$imageu = $image3;
}
?>
<html>
<head>
</head>
<body>
<p>
<?php print $oldip; ?> <br>
<?php print $newip; ?> <br>
Name: <?php print $name; ?> <br>
<img src=<?php print $imageu; ?> /> <br>
Clicks: <?php print $clicks; ?> <br>
Level: <?php print $level; ?> <br>
<?php print $message; ?>
</p>
</body>
</html>
Now the first problem i'm having is with comparing the users ip with the last ip that was on the page.
$newip = $_SERVER['REMOTE_ADDR'];
$oldip = mysql_query("SELECT lastip FROM sitefunctions WHERE name='index'");
if ($newip == $oldip) {
$message = "You were the last one to click this pet, please wait until someone else has clicked it before trying again.";
}
else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='index'");
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='index'");
$tempclicks = mysql_query("SELECT `clicks` FROM sitefunctions WHERE name='index'");
$message = "You gave this pet a click!";
};
No matter what i have tried it doesnt really compare the values. If i put a "=" it says theyre the same no matter what and if i do "==" it says theyre different even though they shouldn't be.
I dont even know where to start with this, no errors come up and i'm fairly new to PHP and MYSQL. Nothing else can be really tested until this, but im sure that the rest of the comparisons dont work either.
im using 000webhost for my site, if thats known to have problems lol
This is what my code looks like now, it works too so im done here:
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
$name = $_POST['name'];
if (empty($name) == true){
$name = "index";
};
include_once "mysql_connect.php";
$newip = $_SERVER['REMOTE_ADDR'];
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$lastip = $row["lastip"];
}
if ($lastip == $newip) {
$message = "You were the last one to click this pet! You have to wait until someone else clicks it!";
} else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='$name'") or die(mysql_error());
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='$name'") or die(mysql_error());
$message = "You clicked the pet!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$clicks = $row["clicks"];
$level = $row["level"];
}
if ($clicks > 50*$level) {
mysql_query("UPDATE sitefunctions SET `level` = `level`+1 WHERE name='$name'") or die(mysql_error());
$message = "Your click leveled up the pet!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$clicks = $row["clicks"];
$level = $row["level"];
$name = $row["name"];
$image1 = $row["image1"];
$image2 = $row["image2"];
$image3 = $row["image3"];
$lastip = $row["lastip"];
};
if ($level > 35) {
$imageu = $image3;
} elseif ($level > 15) {
$imageu = $image2;
} elseif ($level > 0) {
$imageu = $image1;
};
?>
<html>
<head>
</head>
<body>
<center>
<p>
Name: <?php print $name; ?> <br>
<img src=<?php print $imageu; ?> /> <br>
Clicks: <?php print $clicks; ?> <br>
Level: <?php print $level; ?> <br>
Last User: <?php print $lastip; ?> <br>
<?php print $message; ?>
</p>
</center>
</body>
</html>
first time I've used this site .. I've had a good look around but I cant seem to find the answer to my question. It's been answered in other ways but not for what I want I think..
Image of the database table so it's easy to see: http://puu.sh/6BtmZ.png
So basically I've got a friends.php page that has an input field and submit button, you put a username in and press submit and I want it to send a request to that user; I've got that to work, the user can accept but it only places the "friend" into him. As in FRIENDA is friends with FRIENDB but on FRIENDB's page he isn't friends with FRIENDA .. I hope this makes sense.
I just basically want it so, you send a request and the person accepts it and BOTH parties can see each other as friends.
<?php
include 'core/init.php';
// check
protect_page();
include 'includes/templates/header.php';
$user_id = $user_data['user_id'];
if (empty($_POST) === false) {
$required_fields = array('username');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'You need to enter a username to send a request!';
break 1;
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === false) {
$errors[] = 'Sorry, the username \'' . htmlentities($_POST['username']) . '\' doesn\'t exist.';
}
}
}
if (isset($_GET['success']) && empty($_GET['success'])) {
echo 'Friend request sent!';
} else {
if (empty($_POST) === false && empty($errors) === true) {
// add friend
$username = $_POST['username'];
$get_userid = mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'");
$row = mysql_fetch_array($get_userid);
$username_id = $row[user_id];
$user_id = $user_data['user_id'];
mysql_query("INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')");
//redirect
header('location: friends.php?success');
//exit
exit();
} else if (empty($errors) === false) {
// output errors
echo output_errors($errors);
}
}
?>
<h1>Friends</h1>
<p>
<h2>Send a friend request:</h2>
<form id="friend_request" action="" method="POST">
<ul>
<li>Username: <input type="text" name="username"><input id="friend_request" type="submit"></li>
</ul>
</form>
</p>
<p>
<h2>Pending requests:</h2>
<?php
if(isset($_POST['decline'])){
$decline_id = $_POST['decline_friend_id'];
$decline_query = "DELETE FROM `users_friends` WHERE `id` = $decline_id";
$accept_result = mysql_query($decline_query);
}
if(isset($_POST['accept'])){
$accept_id = $_POST['accept_friend_id'];
$accept_query = "UPDATE `users_friends` SET `request_pending` = 0 WHERE `id` = $accept_id";
$accept_result = mysql_query($accept_query);
}
$result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 1");
while($requests_row = mysql_fetch_array($result)) {
$get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$requests_row[user_id]'");
$get_username_row = mysql_fetch_array($get_username);
$request_from = $get_username_row[username];
echo 'Request from: ' . $request_from . '<form id="decline" action="" method="POST">
<input type="hidden" name="decline_friend_id" value="' . $requests_row['id'] . '">
<input type="submit" value="Decline" name="decline">
</form>
<form id="accept" action="" method="POST">
<input type="hidden" name="accept_friend_id" value="' . $requests_row['id'] . '">
<input type="submit" value="Accept" name="accept">
</form>';
echo '<br />';
}
?>
</p>
<h2>Your friends:</h2>
<?php
$friends_result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 0");
while($friends_row = mysql_fetch_array($friends_result)) {
$get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$friends_row[user_id]'");
$get_username_row = mysql_fetch_array($get_username);
$friend = $get_username_row[username];
echo $friend . '<br />';
}
?>
</p>
<?php include 'includes/templates/footer.php'; ?>
Hopefully someone might be able to help? Thanks in advance!
What you probably want to do is insert both directions in the friends relationship once both friends have confirmed. So instead of doing this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')
You would do this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id'),('$username_id','$user_id')
This would allow you to do the friend lookup in either direction.
What is unclear to me however is how you store pending friend requests in your database. So what you may ultimately need to do is to insert those relations in the DB and then simply update those DB records to change the value of an "accepted" flag once the friendship has confirmed.
If the structure of "users_friends" table looks like this:
me friends_with request_pending
to get the result (= if the user is your friend):
"SELECT * FROM `users_friends` WHERE (`friends_with` = '$user_id' AND `me`= `$me`) OR (`friends_with` = '$me' AND `me`= `$user_id `) AND `request_pending` = 0"
You check if the user is in friends_with where YOU are in me.. or if the user is in me and you're in friends_with
I'm using some crazy mixture of PHP/JavaScript/HTML/MySQL
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// Display a confirm box saying "Not everyone has entered a bid, continue?"
}
// If confirmed yes run more queries
// Else nothing
What is the best way to have this confirm box display, before completing the rest of the queries?
if($row != NULL) {
?>
<script>alert("not everyone has submitted their bid.");</script>
<?php
}
or
<?php
function jsalert($alert_message){
echo "<script type='text/javascript'>alert('".$alert_message."');</script>";
}
if($row!=null){
jsalert("Not everyone has submitted their bid.");
}
?>
You can't do this in 1 continuous block, as all of the PHP will execute before the confirm (due to server vs. client).
You will need to break these into 2 separate steps and have the client mediate between them:
part1.php:
<?php
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row != NULL) { ?>
<form id="confirmed" action="part2.php" method="post">
<noscript>
<label>Not everyone has entered a bid, continue?</label>
<input type="submit" value="Yes">
</noscript>
</form>
<script type="text/javascript">
if (confirm("Not everyone has entered a bid, continue?")) {
document.getElementById('confirmed').submit();
}
</script>
<?
} else {
include_once('part2.php');
}
?>
part2.php:
<?php
// assume confirmed. execute other queries.
?>
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// more queries here
} else {
echo "<script>alert('Empty result');</script>";
}
Play with this code and you will get it to work eventually. I know you are not looking for just alertbox , instead you are looking for something like "yes or no" informational box. So check this out.
<?php
?>
<html>
<head>
<script type="text/javascript">
function displayBOX(){
var name=confirm("Not everyone has entered a bid, continue?")
if (name==true){
//document.write("Do your process here..")
window.location="processContinuing.php";
}else{
//document.write("Stop all process...")
window.location="stoppingProcesses.php";
}
}
</script>
</head>
<?php
$query = "SELECT * faculty SET submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
echo "<script>displayBox();</script>";
}
?>