How to fix PhpStorm error about undefined variable [duplicate] - php

This question already has answers here:
PHPStorm: undefined variables caused by include/require
(6 answers)
Closed last year.
This is my index file,
<?php
include 'db.php';
$form = read('form');
//echo '<pre>';
//print_r($forms);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<form action="store.php" method="post">
<label>
Username:
<input type="text" placeholder="username" name="username">
</label>
<label>
Password:
<input type="text" placeholder="password" name="password">
</label>
<label>
Email:
<input type="text" placeholder="email" name="email">
</label>
<button type="submit" name="submit">
submit
</button>
</form>
<table>
<?php foreach ($form as $user): ?>
<tr>
<?php foreach ($user as $item) {
echo '<td>' . $item . '</td>';
} ?>
</tr>
<?php endforeach; ?>
</table>
</body>
and this is my db connection file that reads the database:
<?php
$servername = "localhost";
$username = "root";
$password = "mhimlaA#1";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function read($where = '')
{
global $conn;
$sql = "SELECT * FROM `form` $where LIMIT 1000;";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetchAll(PDO::FETCH_ASSOC);
}
I have weird problem in here that PhpStorm shows an error on $conn in the store file. I'm using this file to insert the input text to database:
<?php
print_r($_POST);
unset($_POST['submit']);
include 'db.php';
$form = read('form');
$sql = "INSERT INTO mydb.form(username, password, email) VALUES (:username,:password,:email)";
$stm = $conn->prepare($sql);
$stm->execute($_POST) or die($conn->errorInfo());
header('location: index.php');

PHPStorm is correct. $conn can be undefined if there was a problem connecting to the database. The actual issue is your poor error handling. Never try-catch exceptions if you don't know what to do with them. You are following cargo cult.
You need to either remove the try-catch or throw an exception in the catch block if you really want to prevent credential leak in error logs.
try {
$conn = new PDO("mysql:host=$servername;dbname=mydb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "Connected successfully";
} catch (PDOException $e) {
throw new \PDOException($e->getMessage(), (int) $e->getCode());
}
You should also remove useless bits of code such as or die($conn->errorInfo())

Related

Form not sending data to database

My form for collecting visitors' mails for newsletter is not sending information to my database, instead just adding spaces with index adding up with no data
this is my html code
<form action="php/newsletter.php" method="post" >
<div class="input-group">
<input class="form-control" type="text" id="email" name="email" placeholder="E-mail ... ">
<span class="input-group-btn">
<button class="btn btn-primary subscribe" type="button" value="insert"><i class="pe-7s-paper-plane pe-2x"></i></button>
</span>
</div>
<!-- /input-group -->
</form>
and this is the php
<?php
$servername = "localhost";
$username = "pridedri_news";
$password = "BBIT/7949/1/1630";
$database = "pridedri_NEWSLETTER";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO subscribers (email)
VALUES ('$email')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Request sent successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//$conn = null;
?>
<Doctype! html>
<body>
<a href="http://pridedrivetours.co.ke/">Back</>
</body>
</html>
where could my mistake be?
You haven't defined $email in your PHP script. Also, you should use a prepared statement for queries with user inputs, to prevent SQL injection (http://bobby-tables.com) -> This is kinda important, please read about SQL injection. Its one of the biggest security issues with PHP websites and it allows 3rd persons to delete your whole database in a few seconds.
Also, to access data posted from a form, you always access the $_POST array, while the key ["email"] is the name of the input.
Try this code:
<?php
$servername = "localhost";
$username = "pridedri_news";
$password = "BBIT/7949/1/1630";
$database = "pridedri_NEWSLETTER";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("INSERT INTO subscribers (email) VALUES (:email)");
$sql->bindParam(':email', $_POST["email"]);
// even exec() returnes true or false!!!!
if($conn->exec($sql)) {
echo "Request sent successfully";
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//$conn = null;
?>
<Doctype! html>
<body>
<a href="http://pridedrivetours.co.ke/">Back</>
</body>
</html>
Declare $email before using it in mysql query
$email = $_REQUEST['email'];
I hope it will work for you

PHP only adding Numbers to sql in column of VARCHAR

PHP only adding Numbers to MySQL in column of VARCHAR instead of texts
when using query directly in MySQL it works...but if I use $_POST from HTML, IT fails
I don't know the reason how it is getting failed. what is the problem here ?
<?php
$link=mysqli_connect("localhost","root","","home_ac");
if(mysqli_connect_error()) {
die("error in database");
}
$name =$_POST["name"];
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,$name)";
if(mysqli_query($link, $query)){
echo "done";
}
else {
echo "failed";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" placeholder="enter a name" name="name">
<input type="submit" value="add">
</form>
</body>
</html>
You need quotes around text
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,'$name')";
Please, think about prepared query. It solve quotes problem and protect from SQL injection.
You have to use PHP Prepared Statements or PHP Data Objects (PDO).
For example, using PDO:
<html>
<head>
<meta charset="utf-8">
<title> Example PDO Insert </title>
</head>
<body>
<form method="post" action="" name="myForm" id="myForm">
<input type="text" placeholder="Enter Your Name" name="name" required="required">
<input type="submit" name="submit" value="add">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "home_ac";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ( isset($_POST['submit']) && !empty($_POST['name']) ) {
# code...
$sql = "INSERT INTO test (number,name) VALUES (NULL,'$name')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

Send Form Data to mysqli dtbs using php fails (xampp environment)

Here is a my html form code: The problem is that i can't figure out how to succesfuly submit the form to mysql dtbs using xampp. (Data aren't sent to dtbs).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Form</title>
<meta name="description" content="An interactive form">
</head>
<body>
<form action="test.php" method="post" id="Personalinfo">
<label for="fname">Όνομα:</label>
<input type="text" id="fname" name="firstname" placeholder="Όνομα
Πελάτη..">
<input type="submit" value="Submit">
</body>
</html>
and now my php code:
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Guests (firstname)
VALUES ('?')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Data is not sent in the mysql dtbs! i've been trying for 2 days solving this but nothing... please help!
Kind regards, Thanos
$sql = "INSERT INTO Guests (firstname) VALUES ('?')";
'?' is to substitute in an integer, string, double or blob value.
You placed the '?', but forgot to prepare it using bind_param. More importantly, you have to pass $firstname value into $stmt->bind_param("s", $firstname);
Updated Code
$firstname = $_POST['firstname'];
$sql = $conn->prepare("INSERT INTO Guests (firstname) VALUES (?)");
$sql->bind_param("s", $firstname);
if ($sql->execute() === TRUE) {
Read
Prepared Statements in MySQLi
how to insert into mysql using Prepared Statement with php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Form</title>
<meta name="description" content="An interactive form">
</head>
<body>
<form action="test.php" method="post" id="Personalinfo">
<label for="fname">Όνομα:</label>
<input type="text" id="fname" name="firstname" placeholder="Όνομα
Πελάτη..">
<input type="submit" name="submitForm" value="Submit">
</body>
</html>
**test.php file**
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submitForm'])){
$firstname = $_POST['firstname'];
$sql = "INSERT INTO Guests (firstname)
VALUES ('{$firstname}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}else{
echo "Are you sure you enter a firstname and the name of your html submit is submitForm";
}
$conn->close();
?>

SELECT Prepared statement

I've tried everything that I found on this community and other sites. But I'm still failing to complete my objective.
What I want to achieve:
On one page I have a input box with a button. When I fill in de ID number I want to get all the information out of mysql which is linked with this ID number....For some reason it doesn't work. Any tips or hints?
<?php
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxxx";
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT id, voornaam FROM sollicitatie_form WHERE id= "echo ($_POST['zoek'])"";
// $stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':voornaam', $voornaam, PDO::PARAM_STR);
$stmt->exec($sql);
$result = $stmt->fetchAll();
foreach ($result as $row){
echo "{$row['voornaam']}";
}
}
// use exec() because no results are returned
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
<!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">
<meta http-equiv="Content-Type" /></meta>
<head>
<title>Sollicitatie Formulier</title>
<link href="styletest.css" rel="stylesheet">
</head>
<body>
<div class="form">
<div class="tab-content">
<h1>Sollicitatie Formulier</h1>
<form method="post" enctype="multipart/form-data" >
<div class="top-row">
<div class="field-wrap">
<div class="field-wrap">
<input type="text" name="zoek" value="">
<input type="submit" name="submit" value="zoek">
</div> <!-- /field-wrap-->
</form>
</div><!-- /tab-content-->
</div> <!-- /form -->
</body>
</html>
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
if(isset($_POST['submit'])):
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, voornaam FROM sollicitatie_form WHERE id= :voornaam and city = :city");
// $stmt->bindParam(':id', $id, PDO::PARAM_STR);
//$stmt->bindParam(':voornaam', $voornaam, PDO::PARAM_STR);
$stmt->bindParam(':voornaam',$_POST['zoek'], PDO::PARAM_STR);
$stmt->bindParam(':city',$_POST['city'], PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row){
echo "{$row['voornaam']}";
}
}
// use exec() because no results are returned
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
endif;
?>
<!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">
<meta http-equiv="Content-Type" /></meta>
<head>
<title>Sollicitatie Formulier</title>
<link href="styletest.css" rel="stylesheet">
</head>
<body>
<div class="form">
<div class="tab-content">
<h1>Sollicitatie Formulier</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" >
<div class="top-row">
<div class="field-wrap">
<div class="field-wrap">
<input type="text" name="zoek" value="">
<input type="text" name="city" value="">
<input type="submit" name="submit" value="zoek">
</div> <!-- /field-wrap-->
</div>
</div>
</form>
</div><!-- /tab-content-->
</div> <!-- /form -->
</body>
</html>
If you want to fetch data you have to use SELECT statement not INSERT statement. Please check this answer hope it will helps you.
Edit
Please try again and check any error is showing or not.
FINAL EDIT
Now check it is running properly now, i just run it on my local server.
Updated with 2 parameters
You need to prepare the statement first, use a select (not insert), use a placeholder in the query, and execute the prepared object. Something like:
$stmt = $conn->prepare("select id, voornaam FROM sollicitatie_form WHERE id= :voornaam";
// $stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':voornaam', $voornaam, PDO::PARAM_STR);
$stmt->execute();
should do it. An alternative syntax I usually use is:
$stmt = $conn->prepare("select id, voornaam FROM sollicitatie_form WHERE id= ?";
$stmt->execute(array($voornaam)); //or array(':voornaam' =>$voornaam) if you prefer named placeholders
Also not echo is for outputting. You can concatenate or place a variable in to double quotes and then your PHP string will have the value.
Another example:
echo "{$row['voornaam']}"
can just be:
echo $row['voornaam'];

PHP Forms to update a SQLite3 database

I need some help I am trying to create a PHP form using sqlite3 and I keep on getting a "syntax error, unexpected T_CATCH in post.php on line 10". All I want to do from the php form is update an existing sqlite3 database in the table1 where the column type = p and the column id = 340 with the values from the form.
HTML Code:
<html>
<head>
<title>Update Form</title>
</head>
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
Slot1: <input type="text" name="slot1"><br>
Slot2: <input type="text" name="slot2"><br>
</p>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
$slot2 = sqlite_escape_string($_POST['slot2']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
catch(Exception $e)
{
echo $e->getMessage();
}
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE tabel1 SET Slot1Pos = :slot1, Slot2Pos = :slot2 WHERE Type = P and ID = 340");
$stmt->bindParam(':slot1', $slot1, PDO::PARAM_STR);
$stmt->bindParam(':slot2', $slot2, PDO::PARAM_STR);
$stmt->execute()
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "Form submitted successfully";
}
Looks like you're missing a brace:
try {
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
echo $e->getMessage();
}

Categories