Search bar wont return results [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Cant figure out what's going wrong here, no errors are appearing but nothing is being returned. The search bar should return the names of other users from my database.
Here is Test.php:
<?php
session_start();
?>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function search(partialSearch){
$.ajax({
url:"PHP.php",
type:"POST",
data {partialSearch:partialSearch},
success:function(result){
$("#results").html(result);
}
});
};
</script>
</head>
<body>
<div class="container">
<h3>Find Other users</h3>
<input type="text" name="partialSearch"onkeyup="search(this.value)"/>
<div id="results"></div>
</div>
</body>
</html>
Here is PHP.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "coursework_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$partialSearch = $_POST['partialSearch'];
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($username);
while ($row = $stmt->fetch()) {
$searchResults[] = $username;
echo "<div>".$searchResults."</div>";
}
?>
Here is the SQL table:
CREATE TABLE members (
memberID int(5) NOT NULL AUTO_INCREMENT,
username VARCHAR(65) NOT NULL UNIQUE,
password VARCHAR(65) NOT NULL,
PRIMARY KEY (memberID)
);
Thank you in advance for any help!

Besides the missing colon in
data {partialSearch:partialSearch},
^
which should read as:
data: {partialSearch:partialSearch},
Your PHP/MySQL syntax is off.
You're declaring $row in
while ($row = $stmt->fetch())
but not using it anywhere.
However, that's kind of a bad for a good as you don't need that much code to start with.
Plus, since you're using LIKE, you're not using the right syntax for it.
See the manual on this: http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html
What your code should look like is this:
$partialSearch = "%". $_POST['partialSearch'] ."%";
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()) {
echo $username;
echo "<div>".$searchResults."</div>";
}
Having checked your console and for errors, you'd of seen what was going on or not.
The JS console would have thrown you:
SyntaxError: missing : after property id
If that still doesn't work for you, then you most likely have errors in your database somewhere.
Consult:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php

you seem tyo be using $username twice-
first for the database access
$username = "root";
and then to reference the database results
$stmt->bind_result($username);
which would seem to cause a conflict since $username="root" - try changing the name to a different variable and see if that makes a difference; eg:
$stmt->bind_result($user_name);
also you have not declared $searchResults to be an array before pushing elements into it, add the following before the while loop:
$searchResults = array();

Concatenate $partialSearch with % wildcards.
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$partialSearch = "%". $_POST['partialSearch'] ."%";
$stmt->bind_param('s',$partialSearch);
...

you are also missing a ":" in the Ajax query - should be:
data: {partialSearch:partialSearch},

Related

Getting blank screen when trying to get data form mysql in json format [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
I'm using a php file to get data from mysql database and display that data in json output, while accessing a certain url address like http://example.com/api/users.php
When I use following code I get json response:
<?php
header("Access-Control-Allow-Origin: *");
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
//Connect to MySQL
$mysql = mysqli_connect($servername, $username, $password, $dbname);
$result_array = array();
$sql = "SELECT username FROM users";
$result = $mysql->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
echo json_encode($result_array);
$mysql->close();
?>
But when trying to get multiple cells from "users" row:
$sql = "SELECT username, avatar, email FROM users";
I get a blank screen in my web browser.
What I'm doing wrong?
If the PHP code you posted is returning a valid json when using single field then the basic code is correct. Now when you try to get multiple fields in the query its showing blank screen. This tells me that possibly your SQL $sql = "SELECT username, avatar, email FROM users"; is throwing error. Try to run this sql statement directly on the database, there can be a mistake in column names.
So if the query fails, your $result_array is empty, and hence the json output is blank.

Data entered through html form is not storing in database of phpmyadmin [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm just trying to store the integer (with id as id) that is entered by the user through html form, in database of phpmyadmin using php and mysql . I'm new to mysql and php. I'm sure that something wrong with the database connection code of php only or mysql queries. Database name is testdb and the table name is testdbtable.
My code is below.
<?php
if (isset($_POST['id'])) {
$integ = $_POST['id'];
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO testdbtable (id)
VALUES ('$integ')";
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>SAMPLE TEST2</title>
</head>
<body>
<form method="post">
<label >Enter your integer:</label>
<input type="number" id="id" name="id">
<br>
<br>
<button type="submit">Submit</button>
</form>
You're defining the query but never run it.
Try this:
$sql = "INSERT INTO testdbtable (id) VALUES ('$integ')";
$conn->query($sql);
As Paul T. said, move the } to the end of the script. Otherwise, even if condition is false, You will just prevent definig $integ, but still running all the rest of the code.
Also, user Prepared Statements to make it more secure.
if (isset($_POST['id'])) {
$integ = $_POST['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Use prepared statements to make it more secure
$sql = "INSERT INTO testdbtable (id) VALUES (?)";
// Prepare statement and bind params
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $integ);
// Execute statement
$stmt->execute();
$conn->close();
}
Take a look at Should we ever check for mysqli_connect() errors manually? as #Dharman commented to stop manually error checking.
Before
$conn->close();
you need to run
$conn->query($sql);
This will actually execute the query.
But this is not the end of the story. You have other issues:
Your code is vulnerable to SQL injection attack. Consider changing the line:
$integ = $_POST['id'];
to
$integ = (int)$_POST['id'];
or (better!) learn how to work with prepared statements.
The query will still be invalid. I bet that the datatype of the column "id" in the "testdbtable" is INT and therefore you should not put quotes around its value. So the $sql variable should be:
$sql = "INSERT INTO testdbtable (id) VALUES ($integ)";
And one more thing - move all query-related code inside the if statement. You should not execute the query if the POST variable is not set.
Your <form> tag has no "action" attribute. You should include it so it do an actual post...

How to perform an inner join sql [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Attempting to try and join my table called 'UserCaseMessages' with my other table called 'Comments' using this exact sql command in php:
$sql = "
SELECT UserCaseMessages.DefendantID, Comments.CommentID
FROM UserCaseMessages
INNER JOIN Comments
ON UserCaseMessages.DefendantID = Comments.SenderID
";
$result = $conn->query($sql);
if ($result->num_rows > 0) // ERROR GETS THROWN ON THIS LINE {
}
Here is the connection part to my database (which occurs prior to the query):
$servername = "localhost";
$username = "username";
$password = "password";
// Get the username from the post
$userUsername = $_POST['string'];
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
I get the following error:
PHP Notice: Trying to get property of non-object
I cannot figure out what I am doing wrong here!! Everything is spelled correctly and a checked and checked for any syntax errors and I can't find any, however I am new to this particular method. Please help!
Since you haven't responded to my comments (some 20+ minutes prior to my submitting this), I am posting the following answer.
You didn't choose a database here:
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
so you need to add the database parameter:
$servername = "localhost";
$username = "username";
$password = "password";
$database = "your_DB";
$conn = new mysqli($servername, $username, $password, $database);
Read the manual on connecting with the MySQLi API:
http://php.net/manual/en/function.mysqli-connect.php
Check for errors on the query also:
http://php.net/manual/en/function.mysql-error.php
Plus, make sure the POST array does contain a value. Something in regards to the HTML form you didn't post.
The form's element must contain a matching name attribute:
name="string" and there must be a POST method for <form>.
method="post".
FYI: <form> is the equivalent to <form method="get"> as it defaults to a GET method if POST isn't implied.
Check for errors with error reporting also:
http://php.net/manual/en/function.error-reporting.php
Although, if your form does not have a POST method as I already mentioned, you won't get errors for it, strangely enough.
Sidenote about $userUsername.
That is ambiguous. If you are trying to run a query against that variable, you would need to use a WHERE clause.
I.e.: WHERE column = '$userUsername'

mySQL dropdown using PHP does not display options from database [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I looked at some other questions online and on here related to this, but none seem to really encounter my error exactly.
I wrote my PHP code and implemented it into my HTML, I get the dropdown box appearing, but it doesn't actually want to display any values. Is there any implementations or fixes I should include in my code? How do I get it to work?
My database is called: Treatments
My column in the database that I want displayed is called: Treatment
treatment_dropdown.php
<?php
$hostname = 'host_name';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
$con=mysql_connect($hostname,$username,$password,$dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
$query = "SELECT * FROM `Treatments`";
$result = mysql_query($con, $query);
$options = "";
while ($row = mysql_fetch_array($result)){
$options = $options . "<option>$row[1]</option>";
}
?>
HTML:
<body>
<select>
<?php
echo $options;
?>
</select>
</body>
Consider changing this line:
$query = "SELECT * FROM 'Treatments'";
to use backticks instead of single quotes like so:
$query = "SELECT * FROM `Treatments`";
In my test query I got an error because of this, let me know if that helps.
Add <?php include 'treatment_dropdown.php'; ?> to the top of your HTML file. This should give you access to the the $options string so it can be used in that file. Note that in order for this to work, treatment_dropdown.php needs to be in the same directory as your HTML file. If it is not, the include statement will need to be changed to reflect the appropriate file path.
Do not use mysql_*() functions, they are deprecated. Use mysqli or PDO instead.
No matter which library use use to access mysql, always check for errors within the sql code separately. Errors in the sql code do not result in errors in the php code.
In this particular case the problem is that you included the table in single quotes instead of backticks.
The correct code:
$query = "SELECT * FROM `Treatments`";
Here's what your PHP file should look like:
<?php
$hostname = 'localhost';
$dbname = 'Treatments';
$username = 'root';
$password = '';
$con = mysql_connect( $hostname, $username, $password, $dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
/* No single quotes needed for the table name. */
$query = "SELECT * FROM Treatments";
/* First parameter should be $query not $con */
$result = mysql_query($query, $con);
$options = "";
/* Check if no results exist. */
if ( !$result ) {
die( "NO results found." );
}
while ( $row = mysql_fetch_array($result) ) {
$options .= "<option>$row[treatment]</option>";
}
?>
Notes:
dont use mysql_* functions, they're not secure, use PDO instead.
your table name does not need to be wrapped in single quotes.
mysql_query expects parameter 1 to be the query not the DB connection.
you should probably check if no results are found.

PHP/MySQL to PDO? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm very new to PHP/Mysql and I naturally have a few questions. I was following a youtube tutorial on creating a simple dynamic website that pulls data content from a MySQL database then displays the content on a single PHP index page. I followed this tutorial to the point where I was using PHP/MySQL to connect to the DB, run a query, fetch the query using a fetch_assoc array. but nothing would display in the body of the page. During the trouble shooting process I was advised that I should be using PDO instead of the older MySQL methods. Can someone decipher my current "older" MySQL code and translate it into the proper PDO coding approach so that I can learn to grasp PDO, since it is the future I should start to understand it now :)
index.php:
<?php
// Setup document:
include('config/setup.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?> - test site</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="header">
<?php include('template/header.php'); ?>
</div>
<div class="nav_main">
<?php include('template/nav_main.php'); ?>
</div>
<div class="content">
<?php //include('content/'.$pg.'.php');
// the database connection, our query
$q = "SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
if (!$r) {
die('Invalid query: ' . mysql_error());
}
$page = mysqli_fetch_assoc($r);
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content_body">'.$page['body'].'</div>';
?>
</div>
<div class="footer">
<?php include('template/footer.php'); ?>
</div>
</div>
</body>
</html>
setup.php:
<?php ## Setup Document
// host(or location of the database), username, password, database name
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "localhost";
$username = "atomcmsadmin";
$password = "uniCi2i";
$dbname = "Atom_CMS";
//Connecting to your database
$dbc = mysqli_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysqli_select_db($dbname);
//include('functions/sandbox.php');
if ($_GET ['page'] == '') {
$pg = 'home';}
else {
$pg = $_GET ['page']; }
$page_title = get_page_title($dbc, $pg);
?>
sandbox.php
<?php
// Sandbox Functions
function get_page ($dbc, $pg) {
// the database connection, our query
$q = "SELECT title FROM pages WHERE type = 1, page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content">'.$page['body'].'</div>';
}
function get_page_title ($dbc, $pg) {
$q = "SELECT title FROM pages WHERE type = 1, page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
return $page['title'];
}
?>
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
all you need to change is setting up the connection, check out the tutorial for the syntax
interacting with the database is still mostly the same
I think no one will do the job for you. But I can help you help yourself:
From your code, you'll need to learn these PDO methods:
PDO::__construct()
You'll replace mysqli_connect() and mysqli_select_db() with that.
PDO::prepare(), PDOStatement::bindValue() and PDOStatement::execute()
You'll replace mysqli_query() with them.
PDOStatement::fetch()
You'll replace mysqli_fetch_assoc() with that.
PDO::errorCode() and PDO::errorInfo()
You might want to use one of them or both to cover errors.
Also take a look at PDO book on the PHP manual. You'll learn all the stuff more easier than you think! Good luck!

Categories