Display database search result in html using php? - php

I'm attempting to create a page, where I can search for case files from my database, however, I can't get my code to work.
I already have pages showing all content of the database and where I can add new content.
I've read guides, tutorials and questions on stackoverflow, but can't find an answer on how to proceed.
I have the following php code in searchcasescript.php
<?php
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or
die("connection failed: " . mysqli_connect_error());
mysqli_select_db($conn, $dbname) or die("something went wrong");
if(isset($_GET["form_submit"]))
{
$journalnummer =$_GET["journalnummer"];
$stmt = $conn->prepare("select * from testcases where journalnummer=? ");
$stmt->bind_param("s",$journalnummer);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count >0)
{
$result =$val->fetch_assoc();
print_r($result);
}
else{
echo "wrong number";
}
$stmt->close();
$conn->close();
}
?>
and my html:
<div class="container-fluid">
<div class="form-group">
<form action="searchcasescript.php" method="post">
<label for="journalnummer">Journalnummer:</label>
<input type="text" name="journal" class="form-control" required>
<div class="form-group"> <br>
<input type="submit" name="form_submit" class="btn btn-basic" value="Søg">
</form>
I've had different results depending on my changes to the php, but currently I'm getting nothing. Pressing search opens a new, blank page.
What I would like to end up with was being able to enter full or part of a case number and the search results being displayed on the same or a new page.
Can anyone point me in the right direction to read more about this and/or where to proceed with my code?
And apologies, if I've somehow missed the answer in one of the questions here.
UPDATED WITH "LIKE":
$stmt = $conn->prepare("SELECT * FROM straffesager WHERE journalnummer LIKE ?");
$stmt->bind_param("s", '%' . $journal . '%');

$journalnummer =$_GET["journalnummer"];
Your looking for journalnummer but your input has a name of journal
<input type="text" name="journal" class="form-control" required>
$_POST['journal'];
This is what should contain the number .

Related

Why will my input form not find a matching user to my search inside of my table?

I am trying to create a PHP search that looks through my table (users) and finds the user that matches the name they searched for and displays it on the screen. But the program won't display the user I searched up, and I don't know why. The variables all check out, and I didn't misspell anything in the code or table. My ifelse statement tells me that there is no query result, even though the user in the table and the user I searched are identical. I am using PHPMyAdmin to manage the tables and see changes (if there are any) to the table. The result I wanted was for the program to display the user and email on the page. I can't find a solution, so if you can please tell me!
addnone.php
<?php
include_once 'includes/db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>SCIENCE FAIR</title>
<link rel="stylesheet" href="style.css">
<section class="container grey-text">
<form class="white" action="addnone.php" method="POST">
<tr>
<label>First Name:</label>
<td><input type="text" name="firstname" placeholder="First Name"></td></br>
</tr>
<div class="center">
<td colspan="2"><input type="submit" name="submit" value="Search"></td>
</div>
</form>
<div class="box">
<?php
if (isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$sql = "SELECT * FROM users WHERE name = '%$firstname%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<div>
<p>".$row['name']."<p>
<p>".$row['email']."<p>
</div>";
}
} else {
echo "No users with name $firstname!";
}
}
?>
</div>
</section>
</html>
db_connect.php
<?php
$dbServername = "localhost";
$dbUsername = "scifair";
$dbPassword = "password";
$dbName = "scifair";
// connect to database
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
?>
Use "LIKE" Operator
$sql = "SELECT * FROM users WHERE name LIKE '%$firstname%'";

HTML form not sending data to MySQL using PHP

I have a form in HTML, but it's not setup like normal I guess. I'll post the code form the HTML (PHP) file and the php to send it to the db.
<form action="upload.php" method="POST">
<!-- Name input-->
<div class="form-group">
<label class="control-label" for="name">Name</label>
<div class="">
<input id="name" name="name" placeholder="First and Last Name" class="form-control input-md" type="text" required>
</div>
</div>
<div class="form-group">
<label class=" control-label" for="supportingDoc">Upload Supporting Documentation</label>
<div class="">
<input id="supportingDoc" name="supportingDoc" class="input-file" type="file" style="margin-top: .5em; margin-left: 4em;">
</div>
</div>
<hr>
<!-- Submit -->
<div class="form-group">
<label class="control-label" for="submit"></label>
<div class="">
<button value="Submit" type="submit" id="submit" name="submit" class="btn btn-danger" style="border-radius: 25px;">Submit</button>
</div>
</div>
</form>
Here is my SQL/PHP
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = mysqli_connect("localhost","xxx","xxx","xxx");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_REQUEST['name'])){
// set variables
$name = mysql_real_escape_string($_POST['name']);
$supportingDoc = mysql_real_escape_string($_POST['supportingDoc']);
$sql = "INSERT INTO `tablew` (name, supportingDoc) VALUES ('$name', '$supportingDoc')";
$result = mysqli_query($con,$sql);
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
printf("New record created successfully");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
printf("Error: " . $sql . "<br>" . $con->error);
}
$con->close();
}
?>
I've tried all sorts of variations and nothing is showing in phpmyadmin. I've even replicated from a previous site I created and it still didn't work lol.
I see that there are variables for the login info and still put it in the mysqli, but I've been at this one thing for about 8 hours now and am out of juice, so hopefully someone sees what I messed up on.
Thanks in advance for any help everyone.
===========================================================================
UPDATE:
I made all the changes mentioned above and now get this:
Warning: mysqli_connect(): (HY000/1049): Unknown database
I can see the database in phpmyadmin and Sequel Pro. I've also made sure to set the password and login to 'root'. My code is as follows for login:
$con = mysqli_connect("localhost","root","root","epboarding");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and this is my POST:
if (isset($_REQUEST['submit'])){
// set variables
$name = mysqli_real_escape_string($con, $_POST['name']);
$sql = "INSERT INTO `wos` (name) VALUES ('$name')";
$result = mysqli_query($con,$sql);
Following issues can be there:
Uploading error. Use enctype="multipart/form-data" in form tag.
Correct Mysql_connect details i.e. Username, Password, Dbname.
mysql_real_escape_string is depricated. Use mysqli.
Recheck your column names i.e. name, supportingDoc.
Your html code wrong. Whenever you want to use input type file, you need to put <form> tag to <form enctype="multipart/form-data">. If you re not declaring the enctype, then the PHP cannot read the file.
you have to put
<form enctype="multipart/form-data">
when uploading file . correct your html.
Try This
The issue is after clicked on submit button it's not hitting the (isset($_REQUEST['name']))
Change it
if (isset($_REQUEST['submit'])){ //code here}
because you button name is submit.
Use SQL injection like
$con->real_escape_string($_POST['name']);
for the unknown database error. I simply went to operations in phpmyadmin and changed the name of the database and it worked. give it a try if you haven't fixed the problem yet.
in addition to #tbi
answer
Check php.ini for max post size it cause the POST request to fail if the size exceeds the size set in php.ini
post_max_size=20M
upload_max_filesize=20M
check your SQL connection and your permissions on the DB
use enctype="multipart/form-data" in your form only when you need to upload files (for security reasons)
finally, don't forget to bind your post params to prevent SQL-Injection
Params Binding
If you are using a default account on a local installation, then your connection code will probably look like this:
<?php $con = mysqli_connect('localhost','root','');
mysqli_select_db('epboarding', $con); ?>
use enctype="multipart/form-data" in form tag when you use file type.
<form name="" method="POST" action="" enctype="multipart/form-data">
3.change the following line
if (isset($_REQUEST['name'])){
to
if (isset($_REQUEST['submit'])){
correct the syntax when post data like mysql to mysqli.
From the PhpMyAdmin screenshot, it looks like the database is running on port 8889, meaning you would need:
$con = mysqli_connect("localhost","xxx","xxx","xxx", 8889);
In addition to what the others have said, I thought I'd provide a tidied script and some (hopefully) useful resource for you other issues.
http://php.net/manual/en/mysqli.construct.php
What's wrong with using $_REQUEST[]?
https://www.w3schools.com/sql/sql_injection.asp
As for your unknown database error this is either your database doesn't exist, is incorrectly named in your PHP script or is unavailable through localhost.
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ( $conn->connect_error ) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
// Check if values are set with post rather than request, as this is deprecated and can output unexpected results
if ( isset( $_POST['name'] ) ) {
// Set variables
$name = $_POST['name'];
$supportingDoc = $_POST['supportingDoc'];
// Prepare a statement and bind parameters to prevent sql injection
$stmt = $conn->prepare( "INSERT INTO `tablew` (name, supportingDoc) VALUES (?, ?)" );
$stmt->bind_param( 'sb', $name, $supportingDoc );
if ( $stmt->execute() ) {
echo "New record created successfully";
printf( "New record created successfully" );
} else {
echo "Error: " . $stmt->error;
printf( "Error: " . $stmt->error );
}
$stmt->close();
$conn->close();
}

how to return values from mysql table with ajax and php

I am new to programing. I have one form to create Groups. It has two text fields Code Id and Code description. After submitting it showed me that the Code Id which i entered is already exist and if not it add one record in MySQL table. What I want that when I leave the Id text field at the same time with onchange event and Ajax to search table and alert if the Id already exit and at the same time fill name text box with description of that Code Id. How to do that? My code is
HTML file
...
</style>
<body>
<H1>Create Grup</h1>
<br>
<form action="creategrup.php" method="post">
<p>
<label for="codigo">Grup Id:</label>
<input type="text" required="required" autofocus="autofocus"
maxlength="4" name="codigo" id="codigo">
</p>
<p>
<label for="nombre">Grupo description:</label>
<input type="text" required="required" name="nombre" id="nombre"">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
And PHP is
<?php
include 'connectdb.php';
$nombre=$_POST['nombre'];
$codigo=$_POST['codigo'];
$sql = "select codigogrupo,nombregrupo from grupo where
codigogrupo='$codigo'";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) >0) {
echo "<p><h1><b>Grup Id $codigo allready exist....</h1></b></p><br>";
echo "<a href='creategrup.html'>Go Back</a>";
}
else {
mysqli_query($conn, "insert into grupo(codigogrupo,nombregrupo)
values('$codigo','$nombre')");
if(mysqli_affected_rows($conn)>0){
echo "<p><h1><b>Grup $nombre added</h1></b></p>";
echo "<a href='creategrup.html'>Go Back</a>";
} else {
echo "Grup not added<br>";
echo mysqli_error ($conn);
}
}
?>
Connectdb.php
<?php
$servername = "server name";
$username = "user name";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
?>
Please help me.
You are getting already exist message so that may be confirm that there is another data with same id. For further assistance please knock me

mysql doesn't update information from html/php

The problem I have: I made a "contact" form, which should send data to my database. All works good, no errors after I access the page from localhost, shows the result I wanted to see, but the database (localhost/phpmyadmin/..) doesn't update with any info.
This is my PHP:
if(isset($_POST['insert']))
{
$hostname = 'localhost';
$username = 'root';
$password = '';
$databaseName = 'nig';
$Nume = $_POST['nume'];
$Email = $_POST['email'];
$Telefon = $_POST['telefon'];
$Subiect = $_POST['subiect'];
$Mesaj = $_POST['mesaj'];
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$query = "INSERT INTO `amar` (`nume`, `email`, `telefon`, `subiect`, `mesaj`) VALUES ('$Nume','$Email','$Telefon','$Subiect','$Mesaj')";
$result = mysqli_query($connect,$query);
if($result)
{
echo 'Mesaj trimis.';
}else{
echo 'Mesaj netrimis';
}
mysqli_free_result($result);
mysqli_close($connect);
This is my HTML:
<form action="insert2.php" action="post">
<form role="form">
<div class="form-group">
<label for="nume">Nume complet</label>
<input type="text" class="form-control" name="nume">
</div>
<div class="form-group">
<label for="email">Adresa e-mail</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label for="telefon">Telefon</label>
<input type="text" class="form-control" name="telefon">
</div>
<div class="form-group">
<label for="subiect">Subiect</label>
<input type="text" class="form-control" name="subiect">
</div>
<div class="form-group">
<label for="mesaj">Mesaj</label>
<textarea class="form-control" name="mesaj" rows="8"></textarea>
</div>
<input type="submit" name="insert" class="btn btn-theme" value="insert"></button>
</form>
And the result should be data in my MySQL. but the database isn't getting any data, what am I doing wrong?
You have two form tags, one inside the other.
Change this....
<form action="insert2.php" action="post">
<form role="form">
To this...
<form action="insert2.php" action="post">
Also, please note, your PHP code is open to SQL injection. Never trust user input. Always validate and/or escape user entered data prior to using it in a query. Or better yet, used prepared statements or stored procedures.
Update 1:
OK, sorry to hear this is not working. Please add the following mysqli error debugging so we can see what is happening.
Change this...
$result = mysqli_query($connect,$query);
To this...
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = mysqli_query($connect,$query)
if (!$result)) {
printf("Errormessage: %s\n", mysqli_error($connect));
}
Then run the code and see if you get any errors that may help us.
Update 2:
OK, try another piece of debugging.
After this...
$query = "INSERT INTO `amar` (`nume`, `email`, `telefon`, `subiect`, `mesaj`) VALUES ('$Nume','$Email','$Telefon','$Subiect','$Mesaj')";
Add this...
die($query);
Save and run the code.
You will be given a SQL query. Copy and paste that SQL query and run it in your database management tool (phpMyAdmin for example). See if the record is added when you manually run the query or if you are given any errors.
Let us know the outcome.

Prepared statement returning nothing

I'm trying to confirm if a user submitted valid credentials.
HTML
<form action="assets/php/account/login_user.php" method="post" id="login" class="center">
<div id="register_errorloc"></div>
<div class="form-group">
<input type="text" name="login_username" id="login_username" class="form-control" placeholder="Username" />
</div>
<div class="form-group">
<input type="password" name="login_password" id="login_password" class="form-control" placeholder="Password" />
</div>
<div class="form-group">
<input type="submit" value="login" id="submit_login" class="btn btn-success form-control"/>
</div>
</form>
PHP
$username = trim($_POST['login_username']);
$password = hash('sha512',trim($_POST['login_password']));
//to check if values are correct by myself
echo '<br>' . $username . '<br>' . $password . '<br>';
include_once '../../../assets/php/DB/DBConnect.php';
//check if valid credentials are entered
$stmt = $conn->prepare("SELECT * FROM tbl_users WHERE username = ?");
echo $stmt->bind_param('s', $username);
echo $stmt->execute();
echo $stmt->store_result();
if($stmt->num_rows == 1){
echo 'Good Creds';
}else{
echo 'Bad Creds';
}
When I'm doing this it always shows 0 results. When I change the querystring to
$stmt = $conn->prepare('SELECT * FROM tbl_users WHERE username = "abc"');
I get the result I'm looking for. I'm confused because I'm using the same approach on a different page and it's working like a charm.
Screenshots
Login form
Submitted form
Row I'm looking for
Edit: Added all code.
Edit2: Added screenshots
Edit3: Added Form HTML
Edit4:
Nothing is wrong with the form submit. When I'm hardcoding the variable like this:
$username ='abc';
It still doesn't work
I'm sorry but you posted screenshots that don't help us.
In order to avoid further commenting, am submitting the following.
Your form and its related elements may be failing and require a POST method and that name attributes exist for each of them.
I.e.:
<form method="post" action="???">
<input type="text" name="login_username">
...
Edit:
Try the following, comments are getting too extensive:
$check = $conn->prepare("SELECT * FROM tbl_users WHERE username=?");
$check->bind_param("s", $username);
$check->execute();
$check->store_result();
$row_chqry = $check->num_rows;
if($row_chqry > 0 ) {
echo "Exists";
$check->close();
$conn->close();
}
Edit #2:
OP posted an answer stating that they were using the same variable for their db connection.
Something I would have spotted right away and causing a conflict, had full code been posted. I've seen that happen quite a few times before, and remember posting answers for them too. As to where they are exactly, it would take some time for me to find them; but I do remember posting answers for related questions.
Oh well, problem solved.
Solutions:
Use a different variable for your username(s).
Use unique variables.
I finally found the error:
When connecting to my DB I use:
$servername = "";
$username = "";
$password = "";
$db = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
In my submission script I also use $username. Including the DBconnection file caused my local variable ($username that I get from the form) to be overwritten with the username found in the DBconnect.

Categories