PHP POST with MYSQLI - php

I'm trying a simple upload of datas from a table in a database with mysqli functions and sql.
I don't know what i'm doing of wrong.
This is the HTML code:
<form name="formCompany" method="post" action="AddCompany.php" >
<div class="modal-body">
<div class="container w-75">
<input type="text" id="nameCompany" name="nameCompany"
class="form-control" placeholder="Name" aria-label="Name" aria-
describedby="basic-addon1">
<br/>
<input type="url" id="webCompany" name="webCompany"
min="1900" class="form-control" placeholder="WebSite" aria-label="WebSite"
aria-describedby="basic-addon1">
<br/>
<input type="text" id="placeCompany" name="placeCompany"
class="form-control" placeholder="Place" aria-label="Place" aria-
describedby="basic-addon1">
<br/>
<input type="email" id="emailCompany" name="emailCompany" class="form-control" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1">
<br/>
<input type="text" id="noteCompany" name="noteCompany"
class="form-control" placeholder="Note" aria-label="Note" aria-
describedby="basic-addon1">
</div>
</div>
<div class="modal-footer">
<button type="submit" id="submitCompany" class="btn btn-
primary">Save</button>
</div>
</form>
and this the page "AddCompany.php" :
<?php
include 'DB.php';
$name = $_POST["nameCompany"];
$place = $_POST["placeCompany"];
$web = $_POST["webCompany"];
$email = $_POST["emailCompany"];
$note = $_POST["noteCompany"];
// Inserisce una nuova compagnia
$sql2="SELECT company_id FROM company ORDER BY company_id DESC LIMIT 1;";
$result=mysqli_query($connessione,$sql2);
$row=mysqli_fetch_array($result,MYSQLI_NUM);
$last_id=$row[0];
$id = $last_id+1;
$sql ="insert into company (company_id, name, place, web,email,note) values
('$id','$name','$place','$web','$email','$note');";
$res1=mysqli_query($connessione, $sql);
if($res1 !=FALSE) {
header("Location: Principale.php");
}
else
{
echo "Impossibile aggiungere Compagnia<br>";
echo "<a href='Principale.php'>Clicca Qui</a> per tornare alla pagina
principale.";
}
?>
It always print me the else because it finds $res1=FALSE
Why?

Try this one, you will see what you are doing wrong
DB.php
define ("DB_USER", "Database username");
define ("DB_PASSWORD", "Database password");
define ("DB_DATABASE", "Database name");
define ("DB_HOST", "Hostname");
//# $con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
# $con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_error)
die("Unable to connect to database : ".$con->connect_error);
Change the query executions
$res1=$con->query($sql);
if($res1){
header("Location: Principale.php");
}
else
{
echo "Error -> ".mysqli_error($con);
echo "Impossibile aggiungere Compagnia<br>";
echo "<a href='Principale.php'>Clicca Qui</a> per tornare alla pagina principale.";
}

name is keyword in Mysql you have to us `
your query must to be something like this
$sql ="insert into company (company_id, `name`, place, web,email,note) values
('$id','$name','$place','$web','$email','$note');";

Related

PHP echo an information of user for a two factor login

I'm an amateur at php mysqli queries. So i was working on a 2nd factor login where user inputs their security answer, but I wanted to echo the user's security question on the form, instead I'm ending up echoing the whole security questions of all users on my database. This is literally a cry for help. lol.
HTML CODE
<section id="client-auth-wrapper">
<div class="container">
<div class="card card-container">
<img id="profile-img" class="profile-img-card" src="//ssl.gstatic.com/accounts/ui/avatar_2x.png" />
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" method="post">
<?php include ('second_security.php'); ?>
<span id="reauth-email" class="reauth-email"></span>
<p>Security Question:</p> <?php
$no = 1;
while ($row = mysqli_fetch_array($query)){
echo'
'.$row['security_quest'].'
';
$no++;
}
?>
<input type="text" id="inputAnswer" name="security_ans" class="form-control" placeholder="Security answer" required autofocus>
<button class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="submit">Submit</button>
</form>
</div>
</div>
</section>
PHP CODE
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'econ');
if (!$db) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$user_check = $_SESSION['username'];
$security_quest = $_SESSION['security_quest'];
$ses_sql = mysqli_query($db, "SELECT username FROM admin_users WHERE username = '$user_check'");
$row = mysqli_fetch_assoc($ses_sql);
?>

PHP SQL Form Insert Creation

I am trying to create a simple form that will insert the given data received by my HTML form, into my SQL table named 'Vendors', however I am struggling to work with its functionality.
There are 7 text fields that I am wanting to add to my Vendors table, and these are so named:
vendorName
addressL1 (Line 1)
addressL2
postcode
email
telephone
description
The HTML for this form can be found below:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action="" method="post">
<ul class="form-style-1">
<li>
<label style="color:#4D4D4D;" >Vendor Name <span class="required">*
</span></label>
<center> <input type="text" name="vendorName" class="field-long"
required="required" placeholder="Vendor Name" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Address <span class="required">*
</span></label>
<center> <input type="text" name="addressL1" required="required"
class="field-long" placeholder="Address Line 1" /> </center>
</br>
<center> <input type="text" name="addressL2" required="required"
class="field-long" placeholder="Address Line 2" /> </center>
</br>
<center> <input type="text" name="postcode" required="required"
class="field-short" placeholder="Postcode" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Contact Details <span
class="required">*</span></label>
<center> <input type="text" name="email" required="required"
class="field-long" placeholder="Email Address" /> </center>
</br>
<center> <input type="text" name="telephone" required="required"
class="field-long" placeholder="Phone Number" /> </center>
</select>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Description </label>
<center> <textarea name="description" id="field5" class="field-long
field-textarea" placeholder="Description"></textarea> </center>
</li>
<li>
<center> <input type="submit" class="AddButton" value="POST"></input>
</center>
</li>
</ul>
</form>
</body>
</html>
And the PHP I have used is:
<?php
date_default_timezone_set('Europe/London');
$server = "";
$connectionInfo = array( "Database"=>"");
$conn = sqlsrv_connect($server,$connectionInfo);
if (!$conn)
{
die("Connection failed");
}
$_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$VendorName = $_POST['vendorName'];
$AddressLine1 = $_POST['addressL1'];
$AddressLine2 = $_POST['addressL2'];
$Postcode = $_POST['postcode'];
$VendorEmail = $_POST['email'];
$VendorNumber = $_POST['telephone'];
$VendorDes = $_POST['description'];
$time = time();
$timestamp = date("Y-m-d H:i:s", $time);
$describeQuery = ("INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ('".$VendorName."', '".$AddressLine1."',
'".$AddressLine2."', '".$Postcode."',
'".$VendorEmail."', '".$VendorNumber."',
'".$VendorDes."', '".$timestamp."')");
$results = sqlsrv_query($conn, $describeQuery);
if(sqlsrv_query($conn, $describeQuery))
{
$alert = "Vendor Successfully Added";
echo "<script type='text/javascript'>alert('$alert');
</script>";
}
else
{
echo 'Information not inserted';
}
}
sqlsrv_close($conn);
?>
Each time I submit the form, it goes straight to the 'Information not inserted' ELSE statement and doesn't import the data into my database.
I have removed my server name and database name for precautionary reasons, however I can assure you they are correct as I have worked on a previous project and used the same method of connecting.
Any help on this would be greatly appreciated, and if there are any formatting mistakes, apologies in advance, I am not an avid user of stack overflow.
Use Mysqli Please, I have updated the script.
<?php
$servername = "localhost";
$username = "username";
$password = "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 Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ($VendorName, $AddressLine1, $AddressLine2,$Postcode,$VendorEmail,$VendorNumber,$VendorDes,$timestamp)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>

Fatal error: Function name must be a string in line 12

Edited: This is the error I got.
$categoryName = $_POST['category_name'] ;
$categoryDesc = $_POST['category_desc'] ;
$sql = "INSERT INTO category (category_title, category_desc) VALUES ('$categoryName','$categoryDesc')";
if (mysqli_query($con,$sql))
{
echo 'Inserted successfully';
}
else
{
echo 'Inserted Failed';
}
mysqli_close($con);
?>
The error I got is Fatal error: Function name must be a string in line 12
line 12 : $categoryName = $_POST['category_name'] ;
[EDITED]
dbconnect.php (I am not sure that I am right or wrong because I am using virtual host, that's why my servername is my virtual host name)
<?php
$servername = "wp-one";
$username = "root";
$password = "";
$dbName = "personality_test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
html code
<div class="col-lg-6">
<form role="form" action="../controller/AddCategory&Question.php?create=true" method="post">
<div class="form-group">
<label>Category Name</label>
<input class="form-control" type="text" placeholder="CategoryName" name="category_name" />
</div>
<div class="form-group">
<label>Category Description</label>
<input class="form-control" type="text" placeholder="CategoryDesc" name="category_desc" />
</div>
<div class="form-group input_fields_wrap">
<button class="add_field_button btn btn-default" style="margin-bottom:10px;">Add New Question</button>
<div class="form-group">
<div class="row">
<div class="col-lg-2"><input type="text" placeholder="Number" class="form-control" name="criteria[]"></div>
<div class="col-lg-5"><input type="text" placeholder="Question" class="form-control" name="grade[]"></div>
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
Please help me, Thank You so much
$conn = new mysqli(...);
so you must use $conn instead of $con
if (mysqli_query($conn,$sql))
{
echo 'Inserted successfully';
}
else
{
echo 'Inserted Failed';
}
mysqli_close($conn);
whats your data type for category_title in database?
Your Error in connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
you use $conn and in insert file you use $can instead of $conn...

Adding something in the database(mysql / phpmyadmin) with PHP

i'm making a website. It has a login form, that transfer to the admin section when you're logged in. It works perfectly, it searches everything in the database, it's everything ok. But the register link isn't working properly. The cadastro.php file should do the register to the cadastra_usuario.php and transfer right to the login page if everything went ok. It also should bring a warning if the password don't match or if some space are missing. It doesn't even register in the database and don't do nothing of this. Here's the codes:
The include's and the form of cadastro.php:
<body>
<div class="container container-twelve">
<div class="four columns offset-by-four">
<h1 class="titles">Cadastro</h1>
<?php if(isset($_SESSION["success"])) {?>
<p><?= $_SESSION["success"] ?></p>
<?php }?>
<?php unset($_SESSION["success"]); ?>
</div>
<div class="four columns offset-by-four" id ="login">
<form action="cadastra_usuario.php" method="post">
<label for="nome">Nome</label>
<input type="text" name="nome" placeholder="Digite seu nome">
<label for="email">Email de usuário </label>
<input type="text" name="email" placeholder="Seu email para login">
<label for="senha">Senha</label>
<input type="password" name="senha" placeholder="Sua senha">
<label for="senha2">Repita sua senha</label>
<input type="password" name="senha2" placeholder="Repita sua senha">
<input type="submit" value="Cadastrar">
</form>
<p> << Voltar para o site</p>
<p> Já tenho um cadastro >> </p>
</div>
</div>
</body>
cadastra_usuario.php:
<?php
include('conecta.php');
include('functions.php');
include('function_usuario.php');
$senha = $_POST['senha'];
$senha2 = $_POST['senha2'];
$cadastra = cadastraUsuario();
if($senha != $senha2){
$_SESSION["danger"] = "As senhas não conferem!";
header("Location: cadastro.php");
}
if($cadastra == null){
$_SESSION["danger"] = "Complete todos os campos!";
header("Location: cadastro.php");
} else {
$_SESSION["success"] = "Usuário cadastrado com sucesso.";
header("Location: login.php");
}
?>
and the function:
function cadastraUsuario($conexao, $nome, $email, $senha){
$nome = $_POST['nome'];
$email = $_POST['email'];
$senha = $_POST['senha'];
$conexao = mysqli_connect('mysql.hostinger.com.br','u374984363_ozzy','ozzy#123', 'u374984363_ncars');
$query = "insert into usuarios (nome, email, senha) values ('{$nome}', '{$email}', '{$senha}')";
return mysqli_query($conexao, $query);
}
Hard to tell, but:
function cadastraUsuario($conexao, $nome, $email, $senha)
awaits $conexao which should be the DB connection, right? But when you call the function, you are not giving the connection:
$cadastra = cadastraUsuario($_POST['nome'], $_POST['email'], $_POST['senha']);
This won't work.
Maybe this a solution:
function cadastraUsuario($nome, $email, $senha) {
$query = "insert into usuarios (nome, email, senha) values ('{$nome}', '{$email}', '{$senha}')";
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query($query)) {
echo "Insert failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
}
Some advices from a developer:
Never write $_POST variables directly to the DB. This allows SQL injection aka security issue!
Write a log function and do application logs as much as possible
Check phperror.log for error if you encounter an error

PHP login.php user not working at mysql

i have a problem to login my user is in the database.
i have the form:
<form data-abide method="post" action="confirmar-login.php" id="formlogin" name="formlogin" >
<div class="row">
<div class="small-8">
<div class="row">
<div class="small-3 columns">
<label for="email" class="right inline">E-Mail:</label>
</div>
<div class="small-9 columns">
<input class="radius" type="email" id="email" name="email" placeholder="joao#mail.com" required="">
<small class="error">Field required</small>
</div>
</div>
</div>
<div class="small-8">
<div class="row">
<div class="small-3 columns">
<label for="senha" class="right inline">Senha:</label>
</div>
<div class="small-9 columns">
<input class="radius" type="password" id="senha" name="senha" placeholder="****" required="">
<small class="error">Field required</small>
</div>
</div>
</div>
<div class="small-8">
<div class="row">
<input type="submit" class="button radius " value="Logar">
<a href="cadastro.php" class="button radius " >Cadastrar</a>
</div>
</div>
</form>
When the login form is submitted it activates confirmar-login.php file And it's the code:
the variable $banco it's where is my database name
<?php
session_start();
require_once 'configuracao.php';
$email = $_POST['email'];
$senha = $_POST['senha'];
$conexao -> query("use $banco") or die ("Erro ao selecionar o database");
$result = $conexao -> prepare("SELECT * FROM usuarios WHERE email_usuario = '$email' and senha = '$senha'") or die("Erro ao selecionar o usuário");
if (mysql_num_rows($result) > 0) {
$_SESSION['email'] = $email;
$_SESSION['senha'] = $senha;
header('location:index.php');
} else {
unset($_SESSION['email']);
unset($_SESSION['senha']);
header('location:login.php');
}
?>
in my file configuracao.php has the code:
$conexao = new PDO($dsn, $user, $pass);
I am not find the problem ... the query is returning anything and the code is not entering the IF. That is when I put the email and password it just redirects me to the login ...
you are using PDO so don't use mysql_* see the following:
$prepared = array(
'email' => $_POST['email'],
'senha' = >$_POST['senha']);
$conexao -> query("use $banco") or die ("Erro ao selecionar o database");
$result = $conexao -> prepare("SELECT * FROM usuarios WHERE email_usuario = :email and senha = :senha");
$result->execute($prepared);
if ($result->fetch()) {
official docs
You did not run the ->execute() function of PDO. You can see examples here.
Also, don't mix the pdo functions and the mysql functions of PHP. They are two different ways of connecting to MySQL. In fact, using the mysql functions is no longer recommended and has been replaced by mysqli and pdo.
$result = $conexao->prepare("SELECT * FROM usuarios WHERE email_usuario = ? and senha = ?");
$result->execute(array($email, $senha));
if($result->rowCount() > 0){
$_SESSION['email'] = $email;
$_SESSION['senha'] = $senha;
}

Categories