MySQL query not working while using php variable in where clause - php

I'm new to PHP and MySQL. I am trying to make a simple search form using which I would want to show the results from the database based on the input text entered in the form.
My code is like this:
Form.php
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>test</title>
</head>
<body>
<form action="search.php" method="GET" id="form">
Name: <input type="text" name="name" >
Age:<input type="text" name="age">
Search<input type="submit" name="submit" id="Search" Value="Search">
</form>
</body>
</html>
Connect.php
<?php
$connect = mysql_connect('localhost','$user','$password');
if(!$connect){
die('Could not connect'.mysql_error() );
}
$db_selected = mysql_select_db('test');
if(!$db_selected){
die('wrong'.mysql_error() );
}
?>
Search.php
<?php
include("includes/connect.php");
$name=$_GET['name'];
echo $name;
$query = "SELECT * FROM `cats` WHERE name='\$name'";
$results= mysql_query($query);
if (!empty($results)){
echo "query successful" ;
exit;
}
$row=mysql_fetch_assoc($results);
echo "Age:".$row['age'];
echo "Name:".$row['name'];
?>
The echo $names ouputs the result correctly and so does echo "query successful".
However the
echo "Age:".$row['age'];
echo "Name:".$row['name'];
only echo's the string part and the query does not seem to fetch any results.
I tried changing the mysql_fetch_assoc to mysql_fetch_array, but it does not do anything either. Could anyone tell me what am i doing wrong here. My DB table has two columns and two rows.

You're escaping the $ in the variable by doing \$.
Try:
$query = "SELECT * FROM `cats` WHERE name='$name'";
EDIT
From the discussion below.
The problem with the undefined index is the fact that you are using $row['age'] when really, the column name in the database is Age. Therefore you must use $row['Age'] when referring to the item. The same goes for name.

$query = "SELECT * FROM `cats` WHERE name='" . $name . "'";
or without concatenation
$query = "SELECT * FROM `cats` WHERE name='$name'";

This should work:
$query = "SELECT * FROM cats WHERE name = '$name'";
Also, when you call "exit;" in the following block it will cancel the execution of the rest of your script:
if (!empty($results)){
echo "query successful" ;
exit;
}

Related

Trying to write to a mysql database but it keeps coming up empty set

For a school project I am trying to write to a table called enrolment where the student number and the course they have selected are added after they have been tested to make sure the student name and number exists in another database. No errors are coming up, however when I check my database afterward enrolment says its an empty set. Does anyone have suggestions?
<?php
require 'connect.php';
//making a variable from the user data
$name = $_POST["name"];
$number = $_POST["snumber"];
$course = $_POST["pcourse"];
//linking up the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());
// select all from table student which show student name and number
$squery = "SELECT * FROM student";
$sresult = mysqli_query($link, $squery);
$found = 0;
while ($srow = mysqli_fetch_array($sresult)) {
// testing if the student name and number match the users data
if ($name == $srow['family'] && $number == $srow['uid']) {
$enrol = "INSERT INTO enrolment (uid course) VALUES('$number' '$course')";
$found = 1;
break;
}
}
mysqli_close($link);
?>
<html>
<body>
<form action="index.php" method="post">
<br>
<input type = "submit" value="back" name="back">
</form>
</body>
</html>
index.php (form)
<!DOCTYPE html>
<html>
<body>
<h1>Course Selection</h1><br>
<form action="next.php" method="post">
Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">
<br><br>
Student Number: <input type="text" name= "snumber" required="required" maxlength="9">
<br><br>
<?php
//form
require 'connect.php';
echo "Select a course: <select name = \"pcourse\">\n";
$link = mysqli_connect(HOST, USER, PASS, DB) or die(mysqli_connect_error());
$query = "SELECT * FROM course";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo "<option> $row[code] $row[name] $row[maxenroll]</option><br>";
}
mysqli_free_result($results);
mysqli_close ($link);
echo " </select>\n";
?>
<br><br>
<input type = "submit" value="submit" name= "submit">
</form>
</body>
</html>
Your insert code just a string. You should send to mysql your insert code. Try this
$enrol = "INSERT INTO enrolment (uid, course) VALUES($number, $course)";
$link->query($enrol);
My guess is that when checking the result set from student table - there is no such family and uid in it, which means - in the table. Instead of doing insert right away, try to display matching record from the database - if this is actually what you wanted to find. Then you can check what is actually stored in the database - and you can compare both.
Other thing is - why not limit select to exact that student?
Rebuild your query, something like:
$squery = "select * from student where family='".$name."' and uid='".$number."'".
Then you can check how many records were selected and display that number before doing any inserts.

Data not fetched from MySQL table in PHP

I want to print the name and last name of an ID entered in the text box. Here is the PHP and HTML code:
<head>
<title>
Search your name by ID
</title>
</head>
<?php
if(isset($_POST["searchname"]))
{
$id = $_POST["searchname"];
$connect = new mysqli("localhost","adarsh","Yeah!","adarsh");
$a = mysql_query("Select * from users where id='$id'",$connect);
$row = mysql_fetch_assoc($a);
echo "$row[0] , $row[1] , $row[2]";
}
else
{
echo "error";
}
?>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" maxlength="6" name="searchname">
<input type="Submit" name="Submit">
</form>
</body>
Output when I enter ID:
, ,
There are entries in the MySQL table but I am unable to fetch them. What is wrong with my code?
UPDATE: I have also tried mysql_fetch_array but it is not working.
Main problem is that you're miximg mysqli and mysql. These are absolutely different APIs.
Assuming you have
$id = $_POST["searchname"];
$connect = new mysqli("localhost","adarsh","Yeah!","adarsh");
Next you should:
$result = $connect->query("Select * from users where id='$id'");
Then get results:
while ($row = $result->fetch_assoc()) {
var_dump($row);
}
And of course, instead of directly putting values into your query use prepared statements.
Update:
about mistakes:
Your main mistake is mixing apis. When you use mysql (which is deprecated and you mustn't use it anymore) you can't use any of mysqli functions and vice versa.
Next - as you create mysqli object with new, you should work in object-oriented style, i.e. calling methods from your mysqli object.
Try this:
<html>
<head>
<title>
Search your name by ID
</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" maxlength="6" name="searchname">
<input type="Submit" name="Submit">
</form>
</body>
</html>
<?php
if(isset($_POST["searchname"])){
$id = $_POST["searchname"];
$connect = mysql_connect("localhost","adarsh","Yeah!","adarsh");
$result = mysql_query("Select * from users where id='$id'",$connect);
$row = mysql_fetch_assoc($result);
print_R($row);
}else{
echo "there is something wrong";
}

How do I check my MySQL table to make sure that I don't enter the same thing twice?

Right now I'm trying to create a PHP/MySQL setup that adds a name to a database. I don't want it to add the name to the database if it already exists though. Right now it is adding the name to the database regardless.
I have three files that I use for this.
First is the Names.php file:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<p>What is your full name?</p><input type="text" name="names"><br>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
Next is the Insert.php file:
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$result = mysql_query("SELECT * FROM names_1 ORDER BY names");
if(!$result) {
die('Invalid SELECT query:' .mysql_error());
}
$sql="INSERT INTO names_1 (names) VALUES ('$_POST[names]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_close($con)
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
And lastly there is the NamesAction.php file:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
mysql_select_db("a7068104_world") or die("Cannot connect to database");
?>
<?php
mysql_query("LOCK TABLES names_1 WRITE;");
$result = mysql_query("SELECT * FROM names_1 ORDER BY names DESC LIMIT 100000");
if(!$result) {
die('Invalid SELECT query:' .mysql_error());
}
echo "<table border='2'>
<tr>
<th>Name</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['names'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_query("UNLOCK TABLES;");
mysql_close($con);
?>
<?php include("Footer.php");?>
</div>
</body>
</html>
Please help as I have no idea how to make sure that I don't enter something into the database twice! What I want to do is check the database to make sure it isn't added already, if it is added already send a message to the user and do add it, and if it isn't added already send a message saying it is adding to the database and add it to the database.
Thanks,
leonardude
First of all don't use mysql_* series of functions. But I'm gonna write the following code using them since you are probably more used to them. But seriously, don't use them. Instead use mysqli or PDO.
$name = mysql_real_escape_string($_POST['names']);
$query = "SELECT * FROM names_1 WHERE names='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
//Already in Db
}
else{
$query = "INSERT INTO names_1 (names) VALUES('$name')";
$result = mysql_query($query);
if($result){
//successful
}
else{
//Unsuccessful
}
}
Or just let the database engine handle the task for you by adding a unique constraint to the columns that are to be unique as other answers suggested.
Use the UNIQUE key.
CREATE TABLE someTable(
ID INT PRIMARY KEY,
some_unique_value INT UNIQUE
);
I hope this helps :)
Create unique key for fields you need to be unique in database and try/catch thrown exception when duplicate data is entered.
This check may be done on the database side
ALTER TABLE `names_1`.`names` DROP PRIMARY KEY, ADD PRIMARY KEY (`names`);

Values are not being deleted in a table in php?

Hello im trying to delete which ever value is selected in a drop down list.
I cant seem to understand what is going on
I have 2 pages 1 with my connection and functions to view the table in a drop down (which works) and a delete function (which doesn't seem to work) and another to call the function in and to delete which ever value is selected.
connection.php
<?php
//Connect to the database
function getSQLConnection() {
$mysqlConnection = new PDO('mysql:host=localhost;dbname=isad235_100000', "root", "");
return $mysqlConnection;
}
//Get all results from members table
function getResults($tablename) {
$sql = "SELECT * FROM " . $tablename;
$mysqlConnection = getSQLConnection();
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
//Delete results from members table
function deleteValue($id) {
$sql = "DELETE FROM members WHERE member_id = '$id'";
$mysqlConnection = getSQLConnection();
$ResultSetting = $mysqlConnection->query($sql);
return $ResultSetting;
}
?>
delete.php
<?php
include_once 'connection.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add</title>
</head>
<body>
<h1> Delete a Member from the Members Table. </h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post'>
Delete Member:
<select name='members' value='members'id="Mmembers">
<?php
$results = getResults('members');
if ($results) {
foreach ($results as $row) {
echo '<option value="' . $row['member_id'] . '">' . $row['name'] . '</option>';
}
}
else
echo '<option value="0"0"> No Data</option>';
?>
</select>
<input type="submit" id="delete" value="Delete"/>
<br/>
<br/>
</form>
<?php
if (isset($_POST['members'])) {
$ResultSetting = deleteValue(($_POST['members']));
}
?>
<br/>
<br/>
<form action='index.php' method='GET'>
Go Back:
<input type="submit" name="submit" value="Return"/>
</form>
<br/>
</body>
</html>
I ran your code and don't see any errors with it. Make sure the id column on your 'members' table is called 'member_id'. If there is a discrepancy in the name then the values for the option elements wouldn't be set. Also, the value you just deleted would still appear after the initial page submit. If you reload the page after the submit, you'll see the value has disappeared.

php form not posting to self

I have a simple dropdown menu which posts the result to itself but when i choose one of the options in the drop down menu it does not echo back the result as expected.
I'm sure i've just missed out something simple but can't spot it. Any ideas? The form posts but does not echo back $user_settings.
<?php
include "functions.php";
connect();
$sql="SELECT user_id, user_realname FROM users ORDER BY user_realname ASC";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$name=$row['user_realname'];
$options.="<OPTION VALUE=>".$name.'</option>';
}
if(isset($_POST['submit'])){
$user_realname = $_POST['username_select'];
$user_select = mysql_query("SELECT user_id, user_realname FROM users WHERE user_realname = '$user_realname'")
or die ("Could not get user data");
while($row = mysql_fetch_array($user_select)){
$user_settings = $row['user_id'];
echo $user_settings;
}
}
?>
<html>
<head>
<body>
<form action="<?php echo $PHP_SELF;?>" method="POST">
<tr><label>Choose User to Edit</tr>
<tr><SELECT NAME="username_select"><OPTION VALUE=""></option>User's Name<?php echo $options;?></SELECT></label></tr>
<tr><input type="submit" value="submit" name="submit"></tr>
</form>
<?php echo $user_settings;?>
<br/>
Go Back
</body>
</head>
</html>
User $_SERVER['PHP_SELF'] instead of $PHP_SELF

Categories