This php has been really giving me issues. I want to Echo back the data from the database and i want it to show the main data from the database and i want it to show the data from the database to match the information entered from the database for instance if i enter the name "Paul Mason" and click the search button , it connects to the datbase and echos back the information on the site.
Code i have written shows below.
<html>
<title>Search Records</title>
<head>
<body>
<form name="" id="" method="post" action="search.php"/>
<p> Enter Student name : <input type="text" name="fullname" id="fullname"/>
<input type="submit" name="senda" value="Search Data" />
</form>
<?php
if(isset($_POST['senda'])){
include 'mysqlconn.php';
$con = mysqli_connect($host, $dbuser, $pass, $db) or die('Cannot Connect');
$name = $_POST['fullname'];
$sql = "SELECT * FROM scores WHERE MATCH(fullname) AGAINST('$name')";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
printf("%s (%s)\n", $row['Fullname'] ." ". $row['studentNo'] ." ". $row['SubjectName'] ." ". $row['GPA'] ." ". $row['CGPA'] ." ". $row['SCORE']);
mysqli_free_result($result);
}
mysqli_close($con);
}
?>
</body>
</head>
</html>
Instead it shows something else like this : Error: Can't find FULLTEXT index matching the column list
What ould be wrong, I need someone to correct me programmatically!
There is no FULLTEXT index on the column you are referencing. For a single column search, if you dont wish to create an index, try (converted into a prepared statement for you as well):
for loose match:
$con = new mysqli($host, $dbuser, $pass, $db) or die('Cannot Connect');
$name = $_POST['fullname'];
$query = $con->prepare("SELECT * FROM scores WHERE fullname LIKE '%$name%'");
$query->execute();
For exact match:
$con = new mysqli($host, $dbuser, $pass, $db) or die('Cannot Connect');
$name = $_POST['fullname'];
$query = $con->prepare("SELECT * FROM scores WHERE fullname = '$name'");
$query->execute();
If you do have or create a FULLTEXT index, then it will work but would still recommend preparing the query to prevent injection attacks:
$con = new mysqli($host, $dbuser, $pass, $db) or die('Cannot Connect');
$name = $_POST['fullname'];
$query = $con->prepare("WHERE MATCH(fullname) AGAINST('$name')");
$query->execute();
Related
My program doesn't insert into the database, tried various means, I'm new to php and tried to test myself with this but I'm finding it difficult to get. i think the problem is at the connection to the database but I'm not getting it
<!DOCTYPE html>
<html>
<head>
<title>LIST</title>
</head>
<body>
<h1> TODO LIST </h1>
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
try {
//create a database conneection
$conn = mysqli_connect("localhost", "root", "");
if(!$conn){
die("Database connection failed: ". mysql_error());
}
$sql = "INSERT INTO tasks (task, date, time) VALUES (:task, :date, :time)";
$query = $conn->prepare($sql);
$query->execute(array(':task'=>$task,
':date'=>$date,':time'=>$time));
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>
<form action = "todolist.php" method = "post">
Task: <input type="text" name="task" id="task"><br/>
Date: <input type="date" name="date" id="date"><br/>
Time: <input type="time" name="time" id="time"><br/>
<input type = "submit" value = "submit" name="submit">
</form>
</body>
</html>
You are not select any database.
Try something like this.
$conn = mysqli_connect("localhost", "root", "", "Yourdatabasename");
Are you connected to your database? You do not select any bdd and the logs are the right ones?
Maybe try:
$conn = mysqli_connect("localhost", "root", "", "databasename");
At first, see if you are connected to your database
I am using this way in one of my project. Create a connect.php file and create connection like this:
<?php
$conn = mysqli_connect("localhost", "root", "", "Yourdatabasename");
?>
Now in index.php file check if the submit button is pressed:
<?php
if(isset($_POST["submit"]))
{
// include connection file
include("connect.php");
// get values
$subject = mysqli_real_escape_string($con, $_POST["subject"]);
$comment = mysqli_real_escape_string($con, $_POST["comment"]);
// Insert in database
$query = "INSERT INTO comments(comment_subject, comment_text)VALUES ('$subject', '$comment')";
mysqli_query($con, $query);
}
?>
I'm working on a project where I can use multiple forms on an html page to search and update tables from a mysql database. I have created a basic html form that will run a search on a separate php file. When I try to integrate that same php script into that same html it finds no results. Any help would be appreciated.
basic html
<html>
<body>
<form name="search" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50" />
<input type="submit" name="Submit" value="Search" />
</form>
</body>
</html>
search php
<?php
$database = "dbname";
$username = "name";
$password = "pass";
$host = "host";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error){
die("Failed:" . $conn->connect_error);
}
echo"Successful";
$query = $_POST['search'];
$query = htmlspecialchars($query);
$raw_results = mysqli_query($conn,"SELECT * FROM beers WHERE name LIKE '%".$query."%'");
if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysqli_fetch_array($raw_results)){
echo "<p><h3>".$results['Name']."</h3>".$results['Brewery']."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
This works separated, but if I copy the same php script and insert it into the main html it connects but finds no results. Tried using _GET instead of _POST removed the action field and Ive searched all over for similar issues. If I scale everything completely down it gives me a parse error for $query = htmlspecialchars($query); , any thoughts?
Apply if (isset($query)) {...}. Only when search name is valid can you gain results.
<?php
$query = $_POST['search'];
// Apply validation.
if (isset($query)) {
$query = htmlspecialchars($query);
echo"Successful";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Failed:" . $conn->connect_error);
}
$raw_results = mysqli_query($conn, "SELECT * FROM beers WHERE name LIKE '%" . $query . "%'");
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($results = mysqli_fetch_array($raw_results)) {
echo "<p><h3>" . $results['Name'] . "</h3>" . $results['Brewery'] . "</p>";
}
} else { // if there is no matching rows do following
echo "No results";
}
}
?>
I'm a noob at PHP/MySQL. I've been looking around a lot but I can't figure out what's going wrong. Purpose of the script: update the value of item 1 and item 2 in the database of user with userID entered in txtUser.
I get my script working when I use a "fixed" value near userId in my query. However, when I try to use a variable ($player), it doesn't work. Seems like my variable is empty...
HTML:
<body>
<form id="form1" action="http://www.something.com/TestScript1.php" method="post" enctype="application/x-www-form-urlencoded">
<div>
<button type="submit" id="submit" value="Submit" title="SAVE">SAVE</button>
</div>
<div>
<input id="txtUser" name="txtUser" type="text" />
<input id="txtItem1" name="txtItem1" type="text" />
<input id="txtItem2" name="txtItem2" type="text" />
</div>
</form>
</body>
PHP :
$host = "localhost";
$user = "username";
$password = "password";
$database = "database";
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
mysqli_select_db($connection,$database) or die ("couldn’t select database");
$item1 = mysqli_real_escape_string($connection,$_POST['txtItem1']);
$item2 = mysqli_real_escape_string($connection,$_POST['txtItem2']);
$query = "UPDATE table SET item1=$item1, item2=$item2 WHERE userId=$player";
$result = mysqli_query($connection,$query)
or die ("couldn’t execute update query: ".mysqli_error($connection));
echo "<h4>Data saved in the database</h4>";
mysqli_close($connection);
?>
Please put this line
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
After $connection
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
Like
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
Because you using $connection variable in mysqli_real_escape_string even before its initialised
$connection is not defined for line
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
please move this line after you create $connection
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
<?php
$host = "localhost";
$user = "username";
$password = "password";
$database = "database";
$conn = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
mysqli_select_db($conn,$database) or die ("couldn't select database");
/* The $conn object must be declared before first / any calls to mysqli_real_escape_string */
$player = mysqli_real_escape_string($conn,$_POST['txtUser']);
$item1 = mysqli_real_escape_string($conn,$_POST['txtItem1']);
$item2 = mysqli_real_escape_string($conn,$_POST['txtItem2']);
/* Values in query should be encapsulated in quotes if they are strings.. are they? */
$query = "UPDATE `table` SET `item1`='$item1', `item2`='$item2' WHERE userId='$player';";
/* Try not to reveal too many details in the event of an error, reduce the attack surface if possible! */
$result = mysqli_query($conn,$query) or die ("update failed: ");
echo "<h4>Data saved in the database</h4>";
mysqli_close($conn);
?>
I am created a small quiz with some functionality and i've ran into a hiccup. I am trying to write into a answers table with information gathered from 2 different tables.
My Question would be is there a way to insert UserId, QuestionId and the answer from the code i have below or can anyone help me with the code I have made.
Sorry if im abit of a noob. Code Below !
So far retrieve username from session
<?php
session_start();
//check if the user is already logged in.
if (!isset($_SESSION['username'])) {
header('Location: index.php');
}
?>
Then retrieve the QuestionId and userId and submit a answer
<section id="content" class="content">
<form action="testingq.php" method="post">
<p>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT QuestionId, QuestionText, InputTypeId FROM question";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> QuestionId: ". $row["QuestionId"]. " - : ". $row["QuestionText"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$host="localhost"; // Host name
$user="root"; // Mysql username
$pass="root"; // Mysql password
$db_name="mydb"; // Database name
// Connect to server and select databse.
$con = mysqli_connect($host, $user, $pass, $db_name);
$sql = "SELECT UserId FROM user WHERE username='$username'";
$result = mysqli_query($con, $sql);
?>
<input type="Radio" name="Answer" value="1" checked/>Yes</p>
<input type="Radio" name="Answer" value="0"/>No</p>
<p><input type="submit" value="Send it!"></p>
</form>
</section>
testingq.php
<!DOCTYPE html>
<html>
<body>
<?php
$host="localhost"; // Host name
$user="root"; // Mysql username
$pass="root"; // Mysql password
$db_name="mydb"; // Database name
// Connect to server and select databse.
$con = mysqli_connect($host, $user, $pass, $db_name);
$sql = "INSERT into answers (QuestionId, UserId, Answer) VALUES(
'$_POST[QuestionId]',
'$_POST[UserId]',
'$_POST[Answer]')";
$result = mysqli_query($con, $sql);
?>
</body>
</html>
I have a database with multiple rows with various fields.
I have a form that contains a drop down list.
The drop down list displays one of the database fields (field_name) for each row in the database.
When the user selects the desired entry hits SUBMIT, that value is passed to the results.php page and can be used via $_POST.
All of this currently works.
I would like a way to send the rest of the row's fields that correspond to the row of the selected field (not just the "field_name") from the database along with what is selected from the drop down menu.
For instance, if I have a database with rows with a fields named "name", "date", and "age", I would like to have all the database rows "name"s appear in the drop down list and once submitted, pass that particular name's "date" and "age" on to the results.php for use on that page.
<html>
<head>
<title>Drop Down Test</title>
</head>
<body style="font-family: verdana; font-size: 11px;">
<?php
//Variables for connecting to database.
$hostname = "abcd";
$username = "abcd";
$dbname = "abcd";
$password = "abcd";
$usertable = "abcd";
//Connecting to database
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
$query = "SELECT * FROM abcd";
$result = mysql_query($query) or die(mysql_error());
?>
<h2>Drop Down Test Form</h2>
<p>Please fill out the form below and click submit.</p>
<form action="results.php" method="POST">
<p>Drop Down Test:
<select name='event'>
<!-- Drop down -->
<?php
while($row = mysql_fetch_array($result))
{
echo '<option>' . $row['field_name']. '</option>';
}
?>
</select>
<p><input type="submit" value="Submit"><p>
</form>
you should put a value on your option like this:
echo '<option value = "'.$row['field_name'].'" name = "">' . $row['field_name']. '</option>';
then you can access it by $_POST['event'];
UPDATE
getting all the values from the select, you can use $_SESSION variables to pass it to the other php.file.
// First of all, I advice you to connect via PDO, or at least msqli, because mysql_query is depreciated.
// To connect with database you need:
DEFINE("USER", "root");
DEFINE("DBNAME", "test");
DEFINE("DBPASSWORD", "");
DEFINE("DBHOST", "localhost");
$dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME,USER,DBPASSWORD,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//The query:
$sth = $dbh->prepare("SELECT name,age,date FROM test");
$sth->execute();
//the drop down form
echo '<form action="results.php" method="POST">
<select name="event"><option value=0></option>';
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) { extract($result);
echo '<option value="date:'.$date.'-age:'.$age.'"/>'.$name.'</option>';
echo '</select>
<p><input type="submit" value="Submit"><p>
</form>';
}
//the event in the records.php by clicking submit
if(isset($_POST['event'])){
echo 'name:',$name'-date:',$date,'-$age',$age;
}
This did the trick (in results.php):
<?php
$hostname = "****";
$username = "****";
$dbname = "****";
$password = "****";
$usertable = "abcd";
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
//it was this SQL query that was the key, namely the WHERE statement
$query = "SELECT * from abcd where field_name='$_POST[event]'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
echo "id: " . $row[0] . "<br/>";
echo "field_name: " . $row[1] . "<br/>";
//etc...
//try to throw the individual results into variables
$variable = $row[1];
echo "Check to see that the variable was passed a value: " . $variable . "<br />";
echo "Check to see that form selection carried over: " . $_POST['event'] . "<br />";
?>
I realize this is not the "up-to-date" way of doing things and I will now try to get everything "modernized".
Thanks for all the help!