problem declaring in php for database in xamp - php

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);
?>

Related

JQuery Autocomplete suggestion retrieved from database

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.

PHP Error Connecting to Database

Background Information:
I am trying to create a TODO App
<?php
require_once 'app/init.php';
$itemsQuery = $db->prepare("
SELECT id, name, done
FROM items
WHERE user = :user
");
$itemsQuery->execute([
'user' => $_SESSION['user_id']
]);
$items = $itemsQuery->rowCount() ? $itemsQuery : [];
foreach ($items as $item) {
echo $item['name'], '<br>';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Darshil Patel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="list">
<h1 class="header">To do.</h1>
<ul class="items">
<li>
<span class="item">Pick Up Shopping</span>
Mark as done
</li>
</ul>
<form class="item-add" action="add.php" method="post">
<input type="text" name="name" placeholder="Add a New Item" class="input" autocomplete="off" required>
<input type="submit" value="Add" class="submit">
</form>
</div>
INIT.PHP:
<? php
session_start();
$_SESSION['user_id'] = 1;
$db = new PDO('msql_dbname= u352634928_list;host=mysql.hostinger.co.uk', 'mysql.hostinger.co.uk', 'password');
if(!isset($_SESSION['user_id'])) {
die('You are not signed in');
}
I am not sure why I am getting this error:
Fatal error: Uncaught exception 'PDOException' with message 'invalid
data source name' in /home/u352634928/public_html/app/init.php:7 Stack
trace: #0 /home/u352634928/public_html/app/init.php(7):
PDO->__construct('msql_dbname=u35...', 'u352634928_list', 'password')
1 /home/u352634928/public_html/index.php(2): require_once('/home/u35263492...') #2 {main} thrown in
/home/u352634928/public_html/app/init.php on line 7
You have left a space between the <? and the php. So at the very first do it <?php
Simple typo:
Change
<? php
To
<?php
Basically, all PHP statements end with semi colon ;.
And in your case, your PHP starts with <? you have added space before php.
So, php is a statement and that is not ended with ;.
That is the reason behind parse error.
change <? php to <?php, remove the space in between.
require_once
pdo
This is the right syntax to connect with Mysql database :
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
for you
$db = new PDO("mysql:host=mysql.hostinger.co.uk;dbname= u352634928_list", 'mysql.hostinger.co.uk', 'password');

PHP search script to pull customer data from mysql

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>

Cannot submit a form on php and mysqli_query

I have a html form that i want to submit its data into a specific database in wamp using phpmyadmin, the connection is successfully done. However, the data cannot be submitted. I get this message after submitting the data in the form :
Successful connection
( ! ) Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in C:\wamp\www\Ex\insert-data.php on line 11
Call Stack
# Time Memory Function Location
1 0.0005 136600 {main}( ) ..\insert-data.php:0
2 0.0023 144480 mysqli_query ( ) ..\insert-data.php:11
Error inserting new records!
My Code in 'insert-data.php' is:
<?php
if(isset($_POST['submitted'])){
include('connect.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert=
"INSERTINTO`test`(`FName`,`LName`)VALUES('$fname','$lname')";
if(!mysqli_query($dbconn,$sqlinsert)){
die('Error inserting new records!');
}
echo "1 record added to database";
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<h1>Insert Data into DB</h1>
</head>
<body>
<form method="post" action="insert-data.php" >
<input type="hidden" name="submitted" value="true" />
<label>First Name</label>
<input type="text" name="fname" />
<label>last Name</label>
<input type="text" name="lname" />
<input type="checkbox" name="check" />
<input type="radio" name="radios" />
<input type="submit" value="submit"></button>
</form>
</body>
</html>
Any idea? ....Thanks
you posted your connection codes in comments (which belongs in your question I might add) being mysql_ based.
You need to use mysqli
those different MySQL APIs do not intermix. You must use the same one from connection to query.
http://php.net/manual/en/function.mysqli-connect.php
Example pulled from the manual:
<?php
//conection:
$link = mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($link));
and remember to replace $link with $dbconn and your own credentials.
This doesn't help you:
die('Error inserting new records!');
this does:
or die(mysqli_error($dbconn));
Since you seem new to this, use prepared statements right away.
References:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Your present code is open to SQL injection.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Just for argument's sake, put a space between INSERT and INTO:
$sqlinsert= "INSERT INTO `test` (`FName`,`LName`) VALUES ('$fname','$lname')";
You seem to have made a reference to that in comments that they are seperated, but I said it anyway.
Plus, try putting your connection/include on top of your conditional statement.
Connection:
Your connection should be this and replacing the xxx with your own credentials.
$db_host = "xxx";
$db_username = "xxx";
$db_pass = "xxx";
$db_name = "xxx";
$dbconn = mysqli_connect("$db_host","$db_username","$db_pass","$db_name")
or die("Error".mysqli_error($dbconn));
and nothing else. No instances of mysql_ at all.
Sidenote: # symbols are error suppressors. You can add them back in once everything is working.
Closing notes:
Kudos to Liam (Sorsby).
Use separated words like,
INSERT INTO `test` (`FName`,`LName`) VALUES ('$fname','$lname')";

PHP/MySQL error for a simple form i made for testing (i'm trying to teach myself some MySQL/PHP)

OK, so, first of all, i'm new to PHP and MySQL so i'm sorry if i'm going to ask some stupid questions:
The page i am trying to create has 4 forms, and a submit button, and i want to send all this info to the database when i click submit, but i have these errors:
Notice: Undefined index: submit in C:\XAMPP\htdocs\SQLtesting\index.php on line 37
Notice: Undefined variable: sql in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
Warning: mysqli_query(): Empty query in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
Here is the code:
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="abcde" />
<title>Untitled 2</title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="User">
First Name:
<input type="text" name="firstName" /> <br />
Last Name:
<input type="text" name="lastName" /> <br />
E-mail:
<input type="text" name="email" /> <br />
Phone Number:
<input type="text" name="phoneNumber" /> <br />
<input type="submit" name="submit" />
</form>
<?php
$con=mysqli_connect("localhost","root",'',"test_1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phoneNumber = $_POST['phoneNumber'];
}
if($_POST['submit'])
{
$sql="INSERT INTO test_1_1(id,firstName, lastName, email, phoneNumber)
VALUES
('','$_POST[firstName]','$_POST[lastName]','$_POST[email]', '$_POST[phoneNumber]')";
echo "1 record added";
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
</body>
</html>
I also noticed that if i write the
$sql="INSERT INTO test_1_1(id,firstName, lastName, email, phoneNumber)
VALUES
('','$_POST[firstName]','$_POST[lastName]','$_POST[email]', '$_POST[phoneNumber]')";
simply without an if conditional i won't get the
Warning: mysqli_query(): Empty query in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
error but the code would add an empty row at the beginning.
I am using XAMPP for running this on local machine.
You have to make sure that $_POST['submit'] is set before you attempt to run the query. Try:
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phoneNumber = $_POST['phoneNumber'];
$sql = "INSERT INTO test_1_1 (id,firstName, lastName, email, phoneNumber)
VALUES ('','$firstName','$lastName','$email', '$phoneNumber')";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
By the way, your code is open to SQL injection. You can solve this security flaw by getting yourself familiar with prepared statements.
Chances are high that the:
if($_POST['submit']) {}
return false and your $sql var isn't filled
Try to add
var_dump($sql);
right before the
if (!mysqli_query($con,$sql))
Everything is related to everything. At first - use function such as var_dump to dump the content of $_POST.
I don't see the reason why $_POST['submit'] is empty, but I'd add some value to it:
<input type="submit" name="submit" value="Hey!" />
Check the condition and the brackets, it doesn't make sense. See Wayne Whitty's answer is correct.
Personally I'd recommend you using some php framework although you spend more time on it. They usually contain a lot of examples, documentation and they are very often aiming to learn you some good habits (coding style, ...).
Notice: Undefined index: submit in C:\XAMPP\htdocs\SQLtesting\index.php on line 37
This means $_POST['submit'] does not exist. You should check if it exists using isset(...) instead of using it directly if you don't want to get the warning.
Notice: Undefined variable: sql in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
Since $_POST['submit'] does not exist, the if clause is not executed and $sql is not filled, the error is self explanatory here.
Warning: mysqli_query(): Empty query in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
This means query string ($sql is not defined and therefore defaulted to an empty string) is empty.

Categories