Dynamic insert into DB - php

i'm creating a simple web app which a form to insert data in DB ( Postgres).
I have this tables:
prenotazione (id,nome_rich,cogn_rich,email_rich,oggetto_rich)
interni (id,nome_int,cogn_int,email_int)
esterni (id,nome_est,cogn_est,email_est)
Now about the tables "interni" and "esterni" the users should choose how many data want to insert, so i have implemented a dynamic form:
**index.php
<div id="start">
<div id="first">
Nome:<input type="text" name="iname[]" size="20"><br>
Cognome: <input type="text" name="isurname[]" size="20"><br>
Email: <input type="email" name="iemail[]" size="20"><br>
<br>
</div>
</div>
<br>
<b> Numero partecipanti interni:</b>
<input type="text" id="n1" value="1"><br>
<button>Aggiungi partecipante</button>
</div>
**input.php
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$testo = $_POST['testo'];
//inserting data order
$query1 = "INSERT INTO prenotazione (id,nome_rich, cogn_rich, email_rich,oggetto_rich) VALUES (1,'$name','$surname', '$email','$testo')";
//execute the query here
$result = pg_query($conn, $query1 ); //if you are using pg_query and $conn is the connection resource
// Interni
$query = "";
if( !empty( $_POST['iname'] ) ) {
foreach( $_POST['iname'] as $key => $iname ) {
$isurname = empty( $_POST[$key]['isurname'] ) ? NULL : $_POST[$key]['isurname'];
$iemail = empty( $_POST[$key]['iemail'] ) ? NULL : $_POST[$key]['iemail'];
$query .= " ( '$iname', '$isurname', '$iemail' ) ";
}
}
if( !empty( $query ) ) {
$query2 = "INSERT INTO interni (nome_int, cogn_int, email_int) VALUES ".$query;
$result = pg_query($conn, $query2 );
The problem is that when they try to insert data into "interni" and the data are more than one, they can't and i receive an error. ( basically the table "interni" is empty when they try to insert more than one ).
How can i solve the problem?
Thanks you all

You are missing comma in between VALUES.
This is what you are executing: INSERT INTO table VALUES (stuff) (stuff2) (stuff3)
Correct is: INSERT INTO table VALUES (stuff), (stuff2), (stuff3)
Fix:
$iemail = empty( $_POST[$key]['iemail'] ) ? NULL : $_POST[$key]['iemail'];
if($query != "") {
$query .= ",";
}
$query .= " ( '$iname', '$isurname', '$iemail' ) ";

Related

Session will not show new values

I have been trying to get my session update, I have created a basic update with mysql as well, it updates in the sql database but it will not show the change within the page.
I'm not sure what else to check, because I checked within the chrome settings and it does show a php session id value but if I go into session storage it shows nothing.
transaction.php
<?php
$_title = 'Update profile';
require_once(__DIR__.'../../components/header.php');
session_start();
if(! isset($_SESSION['user_name'])){
header('Location: ../sign_in/sign_in.php');
die();
}
if (!isset($_SESSION["lang"])) { $_SESSION["lang"] = "en"; }
if (isset($_POST["lang"])) { $_SESSION["lang"] = $_POST["lang"]; }
require_once(__DIR__.'../../globals.php');
require_once(__DIR__.'../../db.php');
try{
$db = _db();
}catch(Exception $ex){
_res(500, ['info'=>'System under maintainance','error'=>__LINE__]);
}
$userProduct = $_SESSION['user']['user_id'];
$q = $db->prepare('SELECT * FROM users WHERE user_id = :userID');
$q->bindValue(":userID", $userProduct);
$q->execute();
require "../lan/lang." . $_SESSION["lang"] . ".php";
?>
<form class="style_form" id="update_profile" onsubmit="return false">
<div>
<label for="name"><?=$_TXT[63]?></label>
<input type="text" name="name" value="<?php echo $_SESSION['user']['user_name']?>">
</div>
<div>
<label for="last_name"><?=$_TXT[64]?></label>
<input type="text" name="last_name" value="<?php echo $_SESSION['user']['lastName']?>">
</div>
<div>
<label for="email"><?=$_TXT[65]?></label>
<input name="email" value="<?php echo $_SESSION['user']['email']?>" type="text">
<input type="hidden" name="userId" value="<?php echo $_SESSION['user']['user_id'] ?>">
<button onclick="update()" id="updateButton"><?=$_TXT[60]?></button>
</form>
</section>
<?php
require_once(__DIR__.'../../components/footer.php');
?>
api-transaction.php
<?php
require_once(__DIR__.'../../globals.php');
// Validate name
if( ! isset( $_POST['name'] ) ){ _res(400,['name is required']); }
if( strlen( $_POST['name'] ) < _FRIST_NAME_MIN_LEN ){ _res(400,['name min '._FRIST_NAME_MIN_LEN.' characters']); }
if( strlen( $_POST['name'] ) > _FRIST_NAME_MAX_LEN ){ _res(400,['name max '._FRIST_NAME_MAX_LEN.' characters']); }
// Validate last_name
if( ! isset( $_POST['last_name'] ) ){ _res(400,['last_name is required']); }
if( strlen( $_POST['last_name'] ) < _LAST_NAME_MIN_LEN ){ _res(400,['last_name min '._LAST_NAME_MIN_LEN.' characters']); }
if( strlen( $_POST['last_name'] ) > _LAST_NAME_MAX_LEN ){ _res(400,['last_name max '._LAST_NAME_MAX_LEN.' characters']); }
// Validate email
if( ! isset( $_POST['email'] ) ){ _res(400,['email is required']); }
if( ! filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL ) ){ _res(400,['email is invalid']); }
$db = require_once(__DIR__.'../../db.php');
try{
session_start();
// $userid = $_SESSION['userId'];
// $userid = $_SESSION['user']['user_id'];
$userid = $_POST['userId'];
$db->beginTransaction();
//Change name
$q = $db->prepare('UPDATE users SET user_name = :update_Name WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_Name', $_POST['name']);
$q->execute();
//Change last name
$q = $db->prepare('UPDATE users SET lastName = :update_lastName WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_lastName', $_POST['last_name']);
$q->execute();
//change email
$q = $db->prepare('UPDATE users SET email = :update_email WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_email', $_POST['email']);
$q->execute();
// change phone number
$q = $db->prepare('UPDATE users SET phone_number = :update_phone WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_phone', $_POST['phone_number']);
$q->execute();
$db->commit();
header('Content-Type: application/json');
$response = ["info" => "info has been updated"];
echo json_encode($response);
}catch(Exception $ex){
http_response_code(500);
echo $ex;
echo 'System under maintainance';
exit();
}

In php: change password is not updating in database

I have a task for registration form where I want to change the password. There are no errors, it is changing when I am doing variable dump (var_dump). Also, it is showing changed password on front-end but not updating in database. I have tried a lot to update in database but what am I doing wrong? I think query problem. Can anybody point in the right direction to solve my query problem? Thanks in advance...
<?php
require_once ( "./connect.php" );
if ( !empty ( $_POST ['submit'] ) ) {
$current_password = md5 ( $_POST [ 'current_password' ] );
$new_password = md5 ( $_POST [ 'new_password' ] );
$confirm_password = md5 ( $_POST [ 'confirm_password' ] );
$sql = ( "SELECT `password` FROM `user` WHERE `username` = '$confirm_password' " ) or die ( "Query didn't work" );
$result = $db->query($sql);
$current_password = $result [ 'password' ];
if ( $current_password == $current_password ) {
if ( $new_password == $confirm_password ) {
$sql = ( "update `user` SET `password`='{$confirm_password}' WHERE user_id = $_COOKIE[id]" );
echo 'success!';
} else {
echo 'New passwords doesn t match!';
}
}
} else {
echo 'Current password doesn t match';
}
?>
<form action = "" method = "POST">
Current-Password: <input type = "password" name = "current_password" value = ""/><br><br>
New-Password: <input type = "password" name = "new_password" value = ""/><br><br>
Confirm-Password: <input type = "password" name = "confirm_password" value = ""/><br><br>
<input type="submit" name="submit" value="change password"/>
</form>
// connect.php file
<?php
$db = new mysqli("localhost", "root", "", "registration");
if($db->connect_error){
exit("cannot connect to database");
}
?>
Run the query after $sql
$sql = ( "update `user` SET `password`='{$confirm_password}' WHERE user_id = $_COOKIE[id]" );
$db->query($sql); //this is missing that why no data update
Hi please check this
<?php
require_once ( "./connect.php" );
if ( !empty ( $_POST ['submit'] ) ) {
$current_password = md5 ( $_POST [ 'current_password' ] );
$new_password = md5 ( $_POST [ 'new_password' ] );
$confirm_password = md5 ( $_POST [ 'confirm_password' ] );
$sql = ( "SELECT `password` FROM `user` WHERE `username` = 'shan' " ) or die ( "Query didn't work" );
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$current_password1 = $row["password"];
}
}
if ( $current_password == $current_password1 ) {
if ( $new_password == $confirm_password ) {
$sql = ( "update `user` SET `password`='{$confirm_password}' WHERE user_id = 1" );
$result = $db->query($sql);
echo 'success!';
} else {
echo 'New passwords doesn t match!';
}
}
} else {
echo 'Current password doesn t match';
}
?>
<form action = "" method = "POST">
Current-Password: <input type = "password" name = "current_password" value = ""/><br><br>
New-Password: <input type = "password" name = "new_password" value = ""/><br><br>
Confirm-Password: <input type = "password" name = "confirm_password" value = ""/><br><br>
<input type="submit" name="submit" value="change password"/>
</form>
Some correction are made in your code are following:
make correction in username (currently your using password as username).
use while loop to fetch password form query result.
compare entered current password with db password (use different variables for both).
set cookie before use else accept user id from user (you're using $_COOKIE['user_id'].
execute update query on db.

Update mysql database and skip empty fields

I have two pages, edit.php and editdone.php.
On the edit.php I am able to fill information, which is being sent to editdone.php. That page is then running a query that updates data in the mysql database.
The problem is; if I leave an input field on edit.php empty, editdone.php will then replace the current information in the database with empty data(nothing).
What I want to do is to make the editdone.php update data if something was written in the fields of edit.php. So if I choose to leave some fields empty and for example only fill one field in the form, I want to only update the filled fields with the filled data and NOT replace the not filled field with empty data. Those field should then, if I haven't filled any data in edit.php, keep the already existing data.
edit.php
<?php
if (!empty($error_msg)) {
echo $error_msg;
}
$cn = $_POST['cname'];
?>
<form action="editdone.php" method="POST" enctype="multipart/form-data" name="editdone" onsubmit="return validateForm()">
<input type="hidden" name="namec" value="<?php echo htmlspecialchars($cn); ?>">
<br>
Fyll i Företagets namn: <br>
<input type="text" name="company_name" id="company_name">
<br><br>
Lägg till en logga:
<input type="file" name="image" id="image">
<br><br>
Description:<br>
<textarea name="description" id="description" rows="4" cols="50"></textarea>
<br>
<br>
Fyll i välkomnings meddelande:<br>
<textarea name="welcome_text" id="welcome_text" rows="5" cols="50"></textarea>
<br>
<br>
Fyll i ett tack meddelande:<br>
<textarea name="thanks_message" id="thanks_message" rows="5" cols="50"></textarea>
<br>
<br>
<input type="submit" name="submit" value="Nästa" />
</form>
editdone.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$namenamec = $_POST['namec'];
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
$q = "UPDATE project SET project_name='$company_name', description='$description', image='$image', image_type='$image_type', welcome_text='$welcome_text', thanks_message='$thanks_message' WHERE project_name='$namenamec' ";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<br>Information stored successfully";
}
?>
For every input/textarea in edit.php, insert a <input type="hidden" value="company_name_old> etc... with the previous value. Then in editdone.php, check if the value in POST is empty or not.
<?php
$company_name = $_POST['company_name'];
if($company_name==""){
$company_name=$_POST['company_name_old'];
}
...
?>
1 cheap "hack" is to assign the current value of the field to the value of the input field and then concat the two strings or values together then save that var. to the database.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$company_name = "";
$description = "";
$welcome_text = "";
$thanks_message = "";
$image = "";
$logo = "";
$image_type = "";
$namenamec = $_POST['namec'];
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
if( isset($_FILES) )
{
if( !empty($_FILES) )
{
if( isset($_FILES['image']['tmp_name']) )
{
if( $_FILES['image']['tmp_name'] != "" && !empty($_FILES['image']['tmp_name']) )
{
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
if( $image != "" && !empty($image) )
{
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
}
}
}
}
}
$update_values = array();
if($company_name != "")
$update_values[] = "project_name='".$company_name."'";
if($description != "")
$update_values[] = "description='".$description."'";
if($image != "")
$update_values[] = "image='".$image."'";
if($image_type != "")
$update_values[] = "image_type='".$image_type."'";
if($welcome_text != "")
$update_values[] = "welcome_text='".$welcome_text."'";
if($thanks_message != "")
$update_values[] = "thanks_message='".$thanks_message."'";
$update_values_imploded = implode(', ', $update_values);
if( !empty($update_values) )
{
$q = "UPDATE project SET $update_values_imploded WHERE project_name='$namenamec' ";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<br>Information stored successfully";
}
}
?>
Try replacing your query like this.
$q = "UPDATE project SET ";
$q .= $company_name ? "project_name='$company_name', " : "";
$q .= $description ? "description='$description', " : "";
$q .= $image ? "image='$image'," : "";
... so on(all fields)
$q .= "WHERE project_name='$namenamec'";
Make sure you remove , for last value
you can do like this here i have made only one variable you can check for each posted variable and append the $q variable as on
$q = "UPDATE project SET";
if(isset($_POST['namec']) && $_POST['namec']!=""){
$q.=" project_name='".$_POST['namec']."' ,";
}
$q=rtrim(',',$q);
$q.="WHERE project_name=".$namenamec;

sql checkbox and mulit select filtering

i'm having some problems filtering my users when a search is run.
It has to be possible to select more than one region and gender.
gender is checkboxes and region is a select multiple selector.
In my project all content is dynamic, but thats to much to show here.
the form:
<form action="" method="get">
<input type="checkbox" name="gender[]" value="1"> <!-- male -->
<input type="checkbox" name="gender[]" value="2"> <!-- female -->
<select name="region[]" multiple>
<option value="1">North</option>
<option value="2">East</option>
<option value="3">West</option>
<option value="4">South</option>
</select>
<input type="submit" name="submitSearch" value="Filter">
</form>
The filter function:
<?php
if(isset($_GET['submitSearch']){
user_filter($db);
}
function user_filter($db){
$gender = $_GET['gender'];
$region = $_GET['region'];
$sql = "SELECT name, region, img FROM users WHERE true $gender AND $region";
$stmt = $db->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll();
return $res;
}
?>
Not sure if i have do a loop with the arrays and there is a problem with WHERE true if nothing is set
hope somebody can help me
Thanks
Change your code like this
if(isset($_GET['submitSearch']){
user_filter($db);
}
function user_filter($db){
$gender = implode(",",$_GET['gender']); //Change array to comma separated string so easy to pass in mysql using IN keyword
$region = implode(",",$_GET['region']);
$sql = "SELECT name, region, img FROM users WHERE gender IN($gender) AND region IN ($region)";
$stmt = $db->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll();
return $res;
}
Updated code for conditions
function user_filter($db){
if(isset($_GET['gender']) && $_GET['gender'] !=''){
$gender = implode(",",$_GET['gender']); //Change array to comma separated string so easy to pass in mysql using IN keyword
}
if(isset($_GET['region']) && $_GET['region'] !=''){
$region = implode(",",$_GET['region']);
}
$genderSql = "";
$regionSql = "";
$where = "";
$sql = '';
$sql .="SELECT name, region, img FROM users";
if(isset($_GET['gender']) && $_GET['gender'] !=''){
$genderSql =" gender IN($gender)"; //Note Space at start
}
if(isset($_GET['region']) && $_GET['region'] !=''){
if(isset($_GET['gender']) && $_GET['gender'] !=''){
$regionSql =" AND region IN ($region)"; //Note Space at start
} else {
$regionSql =" region IN ($region)"; //Note Space at start
}
}
if((isset($_GET['gender']) && $_GET['gender'] !='') || (isset($_GET['region']) && $_GET['region'] !='')){
$where =" Where";
$sql .=$where.$genderSql.$regionSql;
}
$stmt = $db->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll();
return $res;
}

undefined index id,fname,lastname in php

<html><head>
<title>Add record to my_database/my_table</title></head>
<body>
<?php
$self = $_SERVER['PHP_SELF'];
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
?>
<form action="<?php echo( $self ); ?>" method="post">
ID: <input type="text" name="id" size="3">
First Name: <input type="text" name="fname" size="8">
Last Name: <input type="text" name="lname" size="8"><br>
<input type="submit" value="Submit">
</form>
<?php
if( $id and $fname and $lname)
{
$conn=#mysql_connect( "localhost", "root", "" ) or die( "Err:Conn" );
select the specified database
$rs = #mysql_select_db( "add_record", $conn) or die( "Err:Db" );
create the query
$sql = "insert into my_table ( id, first_name, last_name ) values ( $id, \"$fname\", \"$lname\" )";
execute query
$rs = mysql_query( $sql, $conn );
if( $rs )
{
echo( "Record added:$id $fname $lname" );
}
}
?>
</body></html>
here am getting erro as undefined index id,fname,lastname and when i enter values in this am getting db error
At first when your page load $_POST['id'] value is empty because u ve'nt posted any value in $_POST[];
if(isset($_POST['submit'])){
//all your php code here like below
$self = mysql_real_escape_string($_SERVER['PHP_SELF']);
$id = mysql_real_escape_string($_POST['id']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
}
AND
$sql = "insert into my_table ( id, first_name, last_name ) values ( '$id', '$fname', '$lname' )";
By the way what is your db error??
Those POST values will only be set when the form is POSTed. You can use isset()
$id = isset($_POST['id'])? $_POST['id'] : NULL;
Same for others.
This happens because you have no conditions on that PHP code that will prevent it from executing the first time when the form is loaded. They should only execute when the form is submitted. You can wrap that PHP with
if(isset($_POST))
{
// Your existing database code here
}

Categories