Display database value in array PHP MYSQLi - php

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.

Related

php Real-Time form post submit

Let me explain what I want to.
I want to add a value in a list with db add without page change when I input in form, and click submit.
but in this code, I must refresh one more time to add, and also added twice a time.
How can I do that?
<?php
$conn = mysqli_connect('127.0.0.1','MYID','MYPASS','MYDB');
$sql = "SELECT * FROM MYTABLE";
$rs = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($rs)) {
$list = $list."<li>{$row['title']}</li>";
}
$article = array(
'title' => 'Welcome!',
'description' => 'Hello, Web!'
);
if (isset($_GET['id'])){
$filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
$sql = "SELECT * FROM topic WHERE id={$filtered_id}";
$rs = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rs);
$article['title'] = $row['title'];
$article['description'] = $row['description'];
}
if ($_POST['title'] != null){
$sql_in = "INSERT INTO topic (title, description, created) VALUES ('{$_POST['title']}', '{$_POST['description']}', NOW())";
$rs_in = mysqli_query($conn, $sql_in);
if ($rs_in === false) {
$msg = mysqli_error($conn);
} else {
$msg = 'Success.';
}
} else {
$msg = 'Fill in';
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1>WEB</h1>
<ol>
<?=$list?>
</ol>
<details>
<summary>Create</summary>
<form action="./index.php" method="POST">
<p><input type="txt" name="title" placeholder="title"></p>
<p><textarea name="description" placeholder="description"></textarea></p>
<p><input type="submit"></p>
<p><?=$msg?></p>
</form>
</details>
</body>
</html>
<h2><?=$article['title']?></h2>
<?=$article['description']?>
</body>
</html>
In php realtime isn't a thing but there is a workaround you can use events services like pusher https://pusher.com/docs and receive the events in client side instantly .
there other website offers this so do your search before choosing them also you can always build your event server in node.js , c# , go

mysqli query returns the column name as one row in php

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"]

Getting Data from MySQL Database without Refreshing

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>

php problems in search function

Im trying to add search function.
i want it to work like that: for exmple if i have 5 field, and user wrote only in 2, the search will be based only on 2 field. I mean it not neccesary to write information in all 5 field, i want search will happen only in filled fields.
And now it works only if i will write something in all fields (for now i have 2). And if i will write only in one field it doesnt show anything.
Code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<h1>Поиск</h1>
<form action="search_form.php" method="post">
<p>Направление</p>
<input type="text" name="course" />
<p>Форма обучения</p>
<input type="text" name="form" />
<input type="submit" value="Искать">
</form>
<?php
$db = mysql_connect("localhost", "root", "") or die (mysql_error ());
mysql_select_db("university", $db) or die(mysql_error());
$w = array('TRUE');
if (isset($_POST['course']))
{
$course = $_POST['course'];
$w[] = "course='$course'";
}
if (isset($_POST['form']))
{
$form = $_POST['form'];
$w[]= "form='$form'";
}
$where = implode($w, ' AND ');
$query = ('SELECT * FROM news WHERE '.$where);
$result = mysql_query($query,$db);
if($result !== false)
{
$news = mysql_fetch_array($result);
while($news = mysql_fetch_assoc($result)) {?>
<tr>
<td><?=$news['id']?></td>
<td><?=$news['program']?></td>
</tr><?
}
}
else
{
echo 'Sorry, we didn't find anything.';
}?>
</div>
</body>
</html>
You are vulnerable to SQL injection attacks. Learn about and fix that before you do ANYTHING else with this code.
Plus your logic is faulty: mysql_query() returns false on errors. A query which has no results is NOT an error, and still returns a valid query handle. It'll simply have 0 rows on it.
$result = mysql_query($query);
if ($result === false) {
die(mysql_error());
} else if (mysql_num_rows($result) == 0) {
die("No results");
} else {
... display results
}

If MySQL Result Empty display a confirm box

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>";
}
?>

Categories