I am trying to build a simple search script in my own customer portal, I am trying to build it to search by their phone ESN. I am not very experienced with php, so I am probably missing something small, or making a small mistake.
anyway, when you type in any esn of a phone and hit search, it shows no results at all. here is the simple script I am working with
<?php
$dbserv='********';
$dbuser='********';
$dbpass='********';
$dbdata='********';
$link = mysql_connect($dbserv, $dbuser, $dbpass);
if (!$link) { die('Could not connect: ' . mysql_error());}mysql_select_db($dbdata);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="esn" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['esn'])) {
$esn = mysql_real_escape_string($_REQUEST['esn']);
$sql = "SELECT * FROM phones where phoneserial LIKE '%".$esn."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'ESN: ' .$row['phoneserial'].'<br>';
}
}
?>
</body>
</html>
I noticed I made an error earlier in this line
$esn = mysql_real_escape_string($_REQUEST['esn']);
I had it like this instead
$term = mysql_real_escape_string($_REQUEST['esn']);
and then when you typed a 14 digit esn starting with A10000, it would actually show every esn in our database instead of the one that was searched for and i don't know why.
Forgive me if this is lame, still trying to learn
If $esn was undefined, you'd be searching for a pure wildcard (%%), which would match every possible record. Not that surprising when you look at this code:
$sql = "SELECT * FROM phones where phoneserial LIKE '%".$esn."%'";
Just remove the $esn since you didn't define $esn and instead used $term.
You really shouldn't use mysql_ functions anymore. Learn how to use mysqli or PDO and prepared statements rather than escape string functions.
if u want to find only ONE, strict match, you should replace your query with this
$sql = "SELECT * FROM phones where phoneserial = '{$esn}'";
Don't use mysql, use Mysqli
MySQL extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0
Final well form code is
<?php
$dbserv='********';
$dbuser='********';
$dbpass='********';
$dbdata='********';
$link = mysqli_connect($dbserv, $dbuser, $dbpass,$dbdata);
if (!empty($_POST['esn'])) {
$esn = mysqli_real_escape_string($link$_POST['esn']);
$sql = "SELECT * FROM phones where phoneserial LIKE '%".$esn."%'";;
$r_query = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($r_query))
{
echo 'ESN: ' .$row['phoneserial'].'<br>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="esn" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Related
I am learning to use php, html and xamp. what happens is that I have an error because
does not recognize a statement I make on the page to get the list (query) of what you have
the database. the problem is when on the other page it tells me that empleadoID is not defined, according to this the empleadoID is not defined and i don't know why
here is the list. this is where I define it in the last 2 echo:
<?php
include("basededatos.php");
$conexionbd=conectar_bd();
$query ="SELECT id,nombre,edad FROM empleado;";
$resultado = mysqli_query($conexionbd,$query);
mysqli_close($conexionbd);
?>
<html>
<head>
</head>
<body>
<h1>Lista de empleados</h1>
<ul>
<?php
while ($registro = mysqli_fetch_assoc($resultado))
{
echo '<li>'.$registro['nombre'].' ('.$registro['edad'].'años)';
echo ' Modificar</li>';
echo ' Eliminar</li>';
}
?>
</ul>
</body>
</html>
This is where he tells me that he doesn't exist:
<?php
include("basededatos.php");
$conexionbd = conectar_bd();
$query = "SELECT id,nombre,edad FROM empleado Where id".$_GET['empleadoID']."LIMIT 1";
$resultado=mysqli_query($conexionbd,$query);
mysqli_close($conexionbd);
$registro = mysqli_fetch_assoc($resultado);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modificar Empleado</title>
</head>
<body>
<form action="actualizarempleado.php" method="post" name="nuevoempleado">
Nombre: <input type="text" name="empleado_nombre" value="<?php echo $registro['nombre']?>">
<br>
<br>
Edad: <input type="text" name="empleado_edad" value="<?php echo $registro['edad']?>">
<br>
<br>
<input type="hidden" name="empleado_id" value="<?php echo $registro['id']?>">
<br>
<br>
<input type="submit" name="actualizar empleado">
</form>
</body>
</html>
These are the errors in the second page:
Notice: Undefined index: empleadoID in C:\xampp\htdocs\modificarempleado.php on line 5
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\modificarempleado.php on line 8
You have 2 major problems. First, you are not using prepared statements. Second, you have a typo error in your SQL query, missing =. You can't see the errors because you have not enabled MySQLi errors.
The correct approach would look similar to this
<?php
include "basededatos.php";
// This line should go inside conectar_bd()
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conexionbd = conectar_bd();
// prepared -> bind -> execute -> get result
$query = "SELECT id,nombre,edad FROM empleado Where id=? LIMIT 1";
$stmt = $conexionbd->prepare($query);
$stmt->bind_param('i', $_GET['empleadoID']);
$stmt->execute();
$resultado = $stmt->get_result();
mysqli_close($conexionbd);
$registro = mysqli_fetch_assoc($resultado);
?>
I need to to do autocomplete suggestion for my thesis and the data should be retrieved from database. here is my code but it doesn't work! this is my html file.
<!DOCTYPE HTML>
<html>
<head>
<title>Fetching saved records</title>
<script src="jquery-3.2.1.js"></script>
<script src="typeahead.js"></script>
<script type="text/javascript"> </script>
<script>
$(document).ready(function() {
$('input.city').typeahead({
name: 'city',
remote: 'samp5.php?query=%QUERY'
});
})
</script>
</head>
<body>
<form>
Enter the name to search data:<br/>
<input type="text" name="city" id="city" class="city"
autocomplete="off">
<input type="submit" name="find" id="find" value="Find Data"/>
</form>
</body>
</html>
and this is my php file.
<?php
include "connection.php";
if(isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query("SELECT city, area FROM tbl_loc WHERE city LIKE '%{$query}%' OR area LIKE '%{$query}%'");
$array = array();
while ($row = mysqli_fetch_array($sql)) {
$array[] = array (
'label' => $row['city'].', '.$row['area'],
'value' => $row['city'],
);
}
echo json_encode ($array);
}
?>
I don't know why it doesn't work cause there's no error in my codes.
console errors
mysqli_query() requires 2 arguments, the connection and the query, i.e.:
$sql = mysqli_query($connection, "SELECT city, area FROM tbl_loc WHERE city LIKE '%{$query}%' OR area LIKE '%{$query}%'")
Warning!
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
You may want to...
Add error reporting to the top of your file(s) right after your opening <?php tag
error_reporting(E_ALL);
ini_set('display_errors', 1);
Add error checking, such as or die(mysqli_error($connection)) to your queries and other database operations. If not, you can typically find the issues in your current error logs.
I'm trying to write to a database using CKEditor.. when I press submit it dies and says localhost is currently unable to handle this request.
HTTP ERROR 500
I only want to save the textarea into a row in database so I can then read the row on to another page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<title>Classic editor replacing a textarea</title>
<script src="http://cdn.ckeditor.com/4.6.0/standard-all/ckeditor.js"></script>
</head>
<body>
<form id="editor1" action="save.php" method="post" >
<textarea cols="80" id="editor1" name="editor1" rows="10">
</textarea>
<p>
<input type="submit" value="Submit">
</p>
</form>
<script>
CKEDITOR.replace( 'editor1' );
</script>
</body>
</html>
PHP script
<?php
if(isset($_POST['submit']))
{
// Putting data from form into variables to be manipulated
$text = $_POST['editor1'];
$conn = mysql_connect("localhost","root","root") or die ("Can't connect");
mysql_select_db("managerMessage",$conn);
// Getting the form variables and then placing their values into the MySQL table
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
}
?>
You are not concatenating the value correctly in this statement and also text data in a query like this should be wrapped in quotes
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
This is a corrected verion of your code
mysql_query("INSERT INTO text
(textarea)
VALUES ('" . mysql_real_escape_string($text) . "')");
A simpler piece of code would be to read and probably maintain would be
$t = mysql_real_escape_string($text);
mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
I would be remiss if I did not remind you that
Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
EDIT RE: not saving the data to the database
Add some error checking to your code like so:
$t = mysql_real_escape_string($text);
$result = mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
if ( ! $result ) {
echo mysql_error();
exit;
}
Once you know the error, if one exists, you can start work on fixing it.
<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character`";
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action ="handler.php" method="post">
<label for="character">SELECT A CHARACTER </label>
<select multiple name="character">
<?php while($character = mysqli_fetch_assoc($result1)){?>
<option value ="<?php echo $character['id'];?>"</option>
<?php echo $character['name'];?></option>
<?php }?>
<input type="submit" value="submit"/>
</select>
</form>
</body>
</html>
this is my index page above
<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character` where id = ". $_POST ["character"];
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php while($character = mysqli_fetch_assoc($result1)){?>
<?php echo $character["name"];?><br>;
<?php echo $character["attack"];?><br> ;
<?php echo $character["defense"];?><br>;
<?php } ?>
</body>
</html>
alright here is my handler page the issue I am having is I can select multiple options in my html select on my index page but I am having a problem displaying when multiple characters are selected in my handler page. Does anyone know how to fix this specific issue? I also want the data to displayed in a table which I'm pretty sure I can figure out.
What You actually need is logical approach. You have to ask yourself a question "what You want", "what You need" and "how to do it".
So in Your case You want to compare something but You didn't actually say what exactly You need. So if You're new i can can help You that:
What You need for sure is webpage, where user can select character from a list. But what then? I don't know. You didn't specify so...:
1) Show user a select box to choose character. How to get them? Select from database. This is what You already have.
2) After user select character You need to send this data to the server. How to do it? Use <form> tag like:
<form method="post">
<select name="character">...option list...</select>
<input type="submit" value="Search">
</form>
3) Get data sent by Your form and use them to compare with... something You have.
<?php
if( isset( $_POST['character'] ) ){
// do something with this character
}
?>
4) Show user response like found or not found or something else. Pass this data into some div like:
<?php
$found = 'set this true OR false';
if( $found ){
$message = 'Found it!';
}else{
$message = 'Not_found!";
}
?>
Then in HTML write something like:
<div><?php echo isset( $message ) ? $message : ''; ?></div>
Thats it, rest is up to You. Any simple problem You will solve by searching in Google.
-------- Edit
First of all if You're using multiple select box, the name must be:
<select name="character[]" multiple>
Then Your $_POST['character'] is now an array. You can check its content by:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
Use foreach:
$ids = []; // or $ids = array(); if php version lower than 5.4
foreach( $_POST['character'] as $v ){
$ids []= (int) $v;
}
$query = 'SELECT * FROM `character` where id IN ('. implode(',', $ids) .') ';
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
function redirect(URL)
{
document.location="delete_row.php";
return false;
}
</script>
</head>
<body>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM users");
?>
<table border="1">
<th>Name</th>
<th>Age</th>
<th> </th>
<?php
while($row = mysql_fetch_array($result))
{?>
<tr>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['age'];?></td>
<td>Delete</td>
</tr>
<?php } ?>
</table>
<?php
mysql_close($con);
?>
</body>
</html>
This is the PHP part with file name delete_row.php
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>
The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13
How will the page then know what row to delete? You'll have to send some sort of identifier across to it. If you mean, after it's deleted, get the id to hide again, you can do that with a redirect by using:
header('Location: urlOfPageWithoutQueryString');
You can use a small form, with the "delete" button being a submit button. Set the method to "post." An example:
<form action="delete_row.php" method="post">
<input type="hidden" name="row" value="5">
<input type="submit" value="Delete">
</form>
In your PHP file, you can then use the POST values rather than GET values. This is more correct, as well -- GET actions should be idempotent (i.e. should have no effects except returning the requested information).
You should not use GET for this kind of action at all as GET is considered as being a safe method:
[…] the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval. These methods ought to be considered "safe".
Use a POST form instead where you can use a hidden form control for the ID:
<form action="delete_row.php" method="post">
<input type="hidden" name="id" value="5">
<input type="submit" value="Delete row">
</form>
Apart from the safe method reason, using POST instead of GET is also not that vulnerable against Cross-Site Request Forgery attacks. At that point you should also think about using so called CSRF tokens to further reducing the chances of successful CSRF attacks.
Will this work for you?
Delete
You could also do this:
<script language="javascript" type="text/javascript">
function redirect(URL)
{
if(confirm('Are you sure you wish to delete this item?'))
document.location=URL;
return false;
}
</script>
Delete