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 7 years ago.
Improve this question
I've been working on an SQL project. I have a table with two columns, and a search feature in which the user is asked to enter the username in a simple form. Then my php script echoes the Full Name associated with that username.
Here is the HTML page containing the form:
<html>
<head>
<title>Search Contacts</title>
</head>
<p><body>
<h3>Search Contacts Details</h3>
<p>You may search either by first or last name</p>
<form method="post" action="search.php" id="searchform">
<input type="text" name="username">
<input type="submit" name="submit" value="Search">
</form>
</body>
Here is the php script that echoes the full name:
<?php
$con=mysqli_connect("localhost","root","hidden","users");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username=['username']
$sql="SELECT * FROM `users` WHERE `user` LIKE $username";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
$username =$fieldinfo ['username'];
}
// Free result set
echo $username;
}
mysqli_close($con);
?>
The username is a string, so it needs to be in quotes.
You're also missing a semicolon on the line that assigns to $username, and the value you're assigning should be $_POST['username'].
And if the query fails, you should display the error message containing the reason for the failure.
You're only echoing the last username matched. You should move the echo statement inside the loop.
To make LIKE search for any user whose name contains $username, you need to put the wildcard % characters around the search string used with LIKE.
<?php
$con=mysqli_connect("localhost","root","hidden","users");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username=$_POST['username'];
$sql="SELECT * FROM `users` WHERE `user` LIKE '%$username%'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
$username =$fieldinfo ['username'];
echo $username;
}
}
else
{
die(mysqli_error($con));
}
mysqli_close($con);
?>
But it would be better if you learned to use prepared queries. Here's your code rewritten in this style.
<?php
$con=mysqli_connect("localhost","root","hidden","users");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username=$_POST['username'];
$sql="SELECT username FROM `users` WHERE `user` LIKE CONCAT('%', ?, '%')";
$stmt = mysqli_prepare($con, $sql);
mysql_bind_param($stmt, "s", $username);
if ($result=mysqli_execute($stmt))
{
mysqli_bind_result($stmt, $username);
// Get field information for all fields
while (mysql_fetch($stmt)) {
echo $username;
}
}
else
{
echo mysqli_error($con);
}
mysqli_close($con);
?>
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
So, I am trying to validate whether username and email entered by a user in an html form are correct according to Database
I have a database called testing and a table called info which has two fields:
name and email.
this is the code
<html>
<body>
<form action="conn.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="testing";
$name=$_POST['name'];
$mail=$_POST['email'];
// Create connection
$conn1 = new mysqli($servername, $username, $password, $dbname);
$query='select email from info where name= "$name"';
$results = mysqli_query($conn1,$query);
$row= mysqli_fetch_assoc($results);
echo $row["email"];
$email=$row["email"];
if($mail==$email){
echo " correct values";
}
else
echo " incorrect";
//echo $name, $email;
// Check connection
//if ($conn1->connect_error) {
// die("Connection failed: " . $conn1->connect_error);
//}
//echo "Connected successfully";
$conn1->close();
?>
but the result is always incorrect. The values that i enter in the text boxes match the values in the database.
You should use placeholders, the code would be something like this:
$query = 'SELECT emal FROM info WHERE name = ?';
$stmt = mysqli_stmt_prepare($conn1, $query);
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
$results = mysqli_stmt_get_result($stmt);
For better readable code, read up on the object-oriented mysqli-interface, or better yet use PDO.
alternatively you can use string concatenation like
Update this line
$query='select email from info where name= "$name"';
with
$query='select email from info where name= "'.$name.'" ';
or with
$query="select email from info where name= '".$name."' ";
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},
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this form list:
<form action="">
Inlognaam: <input type="text" name="inlognaam">
</form>
Now i want it that if you put there text in, the text will set into the database.
// Create connection
$con=mysqli_connect("localhost","root","","phpexpr");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$inlognaam = $_POST['inlognaam'];
if(isset($POST['inlognaam'])){
$filename = $_POST['inlognaam'];
}
if(isset($filename)){
echo $filename;
}
$sql = 'INSERT INTO gebruikers (inlognaam) VALUES('.$filename.')';
mysql_query($sql);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
I got this code, but i don't know what there is wrong and what schould be changed.
Can somebody help me please? :)
There are several flaws with your code:
you don't specify a method, so your form will be sent with GET, whereas you use $_POST variables in your PHP code. Use
<form action="" method="POST">
you are mixing mysql_* functions and mysqli_* functions. Don't use the former anymore, those are deprecated. Use either MySQLi or PDO (I prefer the latter). If you can't decide which, this article will help you. If you pick PDO, here is a good tutorial.
you're performing two queries here (resulting in two INSERTs):
mysql_query($sql);
if (!mysql_query($sql,$con))
just catch the value of the first query (and use mysqli_query if you want to use MySQLi).
last but not least, due to your string concatanation of your query, you're open to SQL injection. Switch to prepared statements like this:
$sql = 'INSERT INTO gebruikers (inlognaam) VALUES (?)';
$stmt = $con->prepare($sql);
$stmt->bind_param('s', $filename);
$success = $_stmt->execute();
if ($success) {
…
Use the method name POST at the line <form action="" method="post">
and one thing you have mistake that use $_POST NOT $POST in the line
if(isset($POST['inlognaam'])){
$filename = $_POST['inlognaam'];
}
Here,
When you dont specify method attributes of form tag, then default it will use GET method to post data.
So set or use $_REQUEST to get data from html file which independant of form method.
The form maybe like this <form action="" method="POST">
try it
Can you give us an error if you're getting one? I see that you're using a MySQLI connection but you're putting everything in the database with just a MySQL query.
You need this code:
<form action="" method="POST">
<?php
// Create connection
$con = mysqli_connect("localhost","root","","phpexpr");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQLI: " . mysqli_connect_error();
}
$inlognaam = trim($_POST['inlognaam']);
if(isset($_POST['inlognaam']))
{
$filename = trim($_POST['inlognaam']);
}
if(isset($filename))
{
echo $filename;
}
$sql = 'INSERT INTO gebruikers (inlognaam) VALUES('.$con->real_escape_string($filename).')';
$con->query($sql);
if (!mysqli_query($sql,$con))
{
die('Error: ' . mysqli_error());
}
echo "1 record added";
mysqli_close($con);
?>
I've used OO side of MySQLI because I'm not used to produceral side of MySQLI, apoliges for that and the bad English from my side.
I also see that you didn't declared the action in your form, you need to use POST if you wont that user can post informatie that you can send to your DB.
I have been trying for two days now to figure this one out. I copied verbatim from a tutorial and I still cant insert data into a table. here is my code with form
<font face="Verdana" size="2">
<form method="post" action="Manage_cust.php" >
Customer Name
<font face="Verdana">
<input type="text" name="Company" size="50"></font>
<br>
Customer Type
<font face="Verdana">
<select name="custType" size="1">
<option>Non-Contract</option>
<option>Contract</option>
</select></font>
<br>
Contract Hours
<font face="Verdana">
<input type="text" name="contractHours" value="0"></font>
<br>
<font face="Verdana">
<input type="submit" name="dothis" value="Add Customer"></font>
</form>
</font>
<font face="Verdana" size="2">
<?php
if (isset($_POST['dothis'])) {
$con = mysql_connect ("localhost","root","password");
if (!$con){
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES
('$_POST[Company]','$_POST[custType]','$_POST[contractHours]')";
mysql_query($sql, $con);
print_r($sql);
mysql_close($con);
}
?>
This is my PHPmyadmin server info:
Server: 127.0.0.1 via TCP/IP
Software: MySQL
Software version: 5.5.27 - MySQL Community Server (GPL)
Protocol version: 10
User: root#localhost
Server charset: UTF-8 Unicode (utf8)
PLEASE tell me why this wont work. when I run the site it puts the info in and it disappears when I push the submit button, but it does not go into the table. There are no error messages that show up. HELP
I have improved a little bit in your SQL statement, stored it in an array and this is to make sure your post data are really set, else it will throw a null value. Please always sanitize your input.
in your Manage_cust.php:
<?php
if (isset($_POST['dothis']))
{
$con = mysql_connect ("localhost","root","password");
if (!$con)
{
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$company = isset($_POST['Company'])?$_POST['Company']:NULL;
$custype = isset($_POST['custType'])?$_POST['custType']:NULL;
$hours = isset($_POST['contractHours'])?$_POST['contractHours']:NULL;
$sql = "INSERT INTO cust_profile(Customer_Name,
Customer_Type,
Contract_Hours)
VALUES('$company',
'$custype',
'$hours')
";
mysql_query($sql, $con);
mysql_close($con);
}
?>
First of all, don't use font tags...ever
Secondly, because of this line:
if (isset($_POST['dothis'])) {
It looks like your HTML and PHP are combined into one script? In which case, you'll need to change the action on the form to something like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Plus, you can kill a bad connection in one line:
$con = mysql_connect("localhost","root","password") or die("I died, sorry." . mysql_error() );
Check your posts with isset() and then assign values to variables.
var $company;
if(isset($_POST['Company']) {
$company = $_POST['Company'];
} else {
$company = null;
}
//so on and so forth for the other fields
Or use ternary operators
Also, using the original mysql PHP API is usually a bad choice. It's even mentioned in the PHP manual for the API
Always better to go with mysqli or PDO so let's convert that:
//your connection
$conn = mysqli_connect("localhost","username","password","averyit_net");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours)
VALUES ($company,$custType,$contractHours)";
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Assuming you set these
$stmt = mysqli_prepare($conn, $sql);
$stmt->execute();
$stmt->close();
Someone tell me if this is wrong, so I can correct it. I haven't used mysqli in a while.
Change the $sql to this:
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES ('".$_POST[Company]."','".$_POST[custType]."','".$_POST[contractHours]."')
I've almost completed my login script, but I don't know how to check if the username & password is correct.
Here's my script files.
index.php:
<html>
<body>
<form action="action1.php" method="post">
Username: <input type="text" name="uname">
Password: <input type="password" name="pword">
<input type="submit">
</form>
</body>
</html>
The index.php file is just the page that I use to collect the info from my users for registration.
action1.php:
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die ('Could not connect: ' . mysql_error());
}
mysql_select_db("user1", $con);
$sql="INSERT INTO useri1 (uname, pword)
VALUES
('$_POST[uname]','$_POST[pword]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The action1.php file is just the page that registers the users into the database.
login.php:
<html>
<body>
<form action="checklogin.php" method="post">
Username: <input type="text" name="uname1">
Password: <input type="password" name="pword1">
<input type="submit">
</form>
</body>
</html>
The login.php file is just the page I use for the users to type their login info in.
Now this is my problem, I have no idea of how to check the users login info so they can proceed to the members only area. I'm a newbie & any help is GREATLY appreciated.
Thanks,
--Devin
Firstly you want to use mysqli instead of mysql, because mysql is outdated and no longer actively developed. Secondly you want to start escaping your database queries to stop sql injection. In the code below, I used a session to keep track of the user. You can learn more about sessions here.
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'user1');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$userName = $mysqli->real_escape_string($_POST['uname1']);
/* query database */
$result = $mysqli->query("SELECT `pword` FROM `user1` WHERE `uname` = '".$userName."'");
if ($result->num_rows == 1) {
while ($col = $result->fetch_array(MYSQLI_ASSOC)) {
// This presumes you're storing your passwords in plain text.
// If you hashed your passwords or anything, you would have to do the same to $_POST['pword']
if ($_POST['pword'] == $col['pword']) {
// You could do anything here, but sessions are a way of keeping track of a user.
$_SESSION['userName'] = $_POST['uname1'];
$_SESSION['loggedIn'] = true;
}
}
}
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>
You would run a query along the lines of this:
$user_check_query = "SELECT * FROM useri1 WHERE uname=" . $_POST['uname'] . " AND pword=" . $_POST['pword'] .";";
And if the query returns a value, then they can proceed. If the query returns nothing, they cannot pass. As for the logic, look at the code you have created and see how to create if and else statements to handle the logic.
You need to do a SELECT query - something along the lines of
SELECT STRCMP('{$_POST['pword']}', pword) FROM useri1 WHERE uname = '{$_POST['uname']}'
This should return a value in the range [-1, 1] - if it is not 0, the password is wrong. If there is no rows, the user does not exist.
You need to think about SQL injections as well - but that could very well be an exercise for another day.