Insert data from one table to another in joined table - php

This sends "customers.id" to another php file :
echo '<a class="btn btn-primary" href="createworkorder.php?id='.$row['id'].'">Add Workorder</a>';
This pulls the id date just sent :
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: customers.php");
}
This looks at values/ and inserts data from extra workorder table form post :
$id = $POST['name'];
$date = $_POST['date'];
$installer = $_POST['installer'];
$salesman = $_POST['salesman'];
$category = $_POST['category'];
$status = $_POST['status'];
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO workorder (date, installer, salesman, category, status) values(?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array( $id,$date,$installer,$salesman,$category,$status));
Database::disconnect();
header("Location: workorders.php");
}
<form class="form-horizontal" action="createworkorder.php" method="post">
<div class="control-group <?php echo !empty($dateError)?'error':'';?>">
<label class="control-label">Date</label>
<div class="controls">
<input name="date" type="text" placeholder="Date" value="<?php echo !empty($date)?$date:'';?>">
<?php if (!empty($dateError)): ?>
<span class="help-inline"><?php echo $dateError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($installerError)?'error':'';?>">
<label class="control-label">Installer</label>
<div class="controls">
<input name="installer" type="text" placeholder="Installer" value="<?php echo !empty($installer)?$installer:'';?>">
<?php if (!empty($installerError)): ?>
<span class="help-inline"><?php echo $installerError;?></span>
<?php endif;?>
</div>
</div>
for some odd reason, it looks like everything executes(no errors), but no data shows up in my workorders table. This is what is supposed to happen
Pull customers.id from user selection, and store into workorder.name
Pull extra information(date/installer/salesman/etc) from form, and use all of the data to insert into workorder table.
Does anyone see if there is something dumb causing this not to happen?

It's been awhile since I spoke PHP, but are you inserting too many variables?
Specifically, in the code below, is including $id throwing it off? If you have to include $id, should you modify the INSERT query to include a spot for the id?
$q->execute(array( $id,$date,$installer,$salesman,$category,$status));

Related

PHP Posting an array from a form is not working

I have some checkboxes with printed values according to the database which are working fine.When I submit the form it gives me an error saying that the variable which I posted from the checkboxes array is not defined and that way I cant insert the values in the database.
The PHP code to post the array and insert in the database:
//The posts above don't matter because the first query works just fine
$candCurso = $_POST['curso'];
$query = "INSERT INTO tbl_candidatos(cand_nome, cand_datanasc, cand_nac, cand_nat, cand_gen, cand_morada, cand_codpost, cand_cidade, cand_email, cand_telefone, cand_telemovel, cand_tipodoc, cand_ndoc, cand_valdoc, cand_nif, cand_hablit, cand_sitprof, cand_grau, cand_instgrau, cand_datagrau, cand_instfunc, datainsc) VALUES ('$candNome','$candDataNasc','$candNac','$candNat','$candGen','$candMorada' ,'$candCodPost','$candCidade','$candEmail','$candTelefone','$candTelemovel','$candTipoDoc','$candNDoc','$candValDoc', '$candNif','$candHabLit','$candSitProf','$candGrau','$candInstGrau', ' $candDataGrau','$candInstFunc', '$dins')";
$result = mysqli_query($link, $query); // Executa a instrução MYSQL
if($result){
echo "<script>alert('I entered the result if');</script>";
$lastID = mysqli_insert_id($link);
foreach($candCurso as $value) {
echo "<script>alert('I entered the foreach if');</script>";
$data = date('Y-m-d');
$sql = "INSERT INTO tbl_professor_curso(cand_id, cur_id, data_admissao) VALUES ($lastID, '$value', '$data')";
$rr = mysqli_query($link, $sql); // Executa a instrução
}
The code doesn't run the foreach statement because of the variable $candCurso.
The form:
<!-- Message -->
<div class="col-md-12">
<!-- Form Group -->
<div class="form-group">
<label for="form_message">Select *</label>
<?php
$cursos = getCursos($link);
foreach ($cursos as $curso): ?>
<div class="checkbox">
<label >
<input type="checkbox" class="form-control" name="curso[]" value="<?= $curso['cur_id'] ?>"> <?= $curso['cur_nome'] ?>
</label>
</div>
<?php
endforeach;
?>
</div><!-- /End Form Group -->
</div><!-- /End Message -->
Any help is appreciated as I'm looking to fix this for hours.

How to Save select option value data instead of Id using PHP MYSQL

How best can I save a select option value name instead of the id using just Ajax, PHP and MYSQL.
I tried many ways but for now when I select the data and store back it keeps saving generated id and that's not what I want.
When i decided to change the id of the selection option to value i the values does show on the drop down.
Details.php
<form method="post" name="signup" onSubmit="return valid();">
<label class="control-label">Profile ID</label>
<select id="employee" name="regcode" class="form-control">
<option value="" selected="selected">Select Profile ID</option>
<?php
$sql = "SELECT id,regcode FROM tbstudentprofile";
$query = $dbh->prepare($sql);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<option name="regcode" value="<?php echo $row["id"]; ?>">
<?php echo $row["regcode"]; ?> </option>
<?php } ?>
</select>
<div class=" form-group1 form-last>
<label class=" control-label">Status</label>
<textarea name="status" row="2"></textarea>
</div>
<button type="submit" name="save">Save </button>
</form>
enter code here
query
if (isset($_POST['save'])) {
$regcode = $_POST['regcode'];
$status = $_POST['status'];
$sql = "INSERT INTO studentschooltbl(regcode,status) VALUES(:regcode,:status)";
$query = $dbh->prepare($sql);
$query->bindParam(':regcode', $regcode, PDO::PARAM_STR);
$query->bindParam(':status', $status, PDO::PARAM_STR);
$query->execute();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
$msg = " Registration successfully";
} else {
$error = "error";
}
}

PHP not inserting into database SQL SERVER 2008

I have this form that I want to use to capture data and insert into a database:
<form actoin="request-new-price.php" method="post" id="demo-form2" data-parsley-validate>
<div>
<label for="salesRep">Sales Rep:</label>
<div>
<input type="text" name="salesRep" id="salesRep" required="required" value="<?php echo $user['userName']; ?>">
</div>
</div>
<div>
<label for="CardName">Customer Name</label>
<div>
<input type="text" id="CardName" name="CardName" required="required" value="<?php echo $selectedCustomerName ?>">
</div>
</div>
<div>
<label for="CardCode">Customer Code</label>
<div>
<input type="text" id="CardCode" name="CardCode" required="required" value="<?php echo $selectedCustomerID ?>">
</div>
</div>
<div>
<label for="ItemName">Product Name</label>
<div>
<input type="text" id="ItemName" name="ItemName" required="required" value="<?php echo $selectedProductName ?>">
</div>
</div>
<div>
<label for="ItemCode">Product Code</label>
<div>
<input type="text" id="ItemCode" name="ItemCode" required="required" value="<?php echo $selectedProductCode ?>">
</div>
</div>
<div>
<label for="Price">Current Price</label>
<div>
<input type="text" id="Price" name="Price" required="required" value="£<?php echo $selectedProductPrice ?>">
</div>
</div>
<div>
<label for="requestedPrice">Requested Price</label>
<div>
<input type="text" id="requestedPrice" name="requestedPrice" required="required" value="£">
</div>
</div>
<div>
<div>
Cancel
<button type="submit" id="submit" name="submit" value="1">Submit</button>
</div>
</div>
</form>
And here is my SQL/PHP:
<?php
if(isset($_POST['submit'])){
print_r($_POST);
$query = prepare("INSERT INTO PriceRequests (salesRep, CardName, CardCode, ItemName, ItemCode, Price, requestedPrice)
VALUES (:salesRep, :cardName, :cardCode, :itemName, itemCode, :itemPrice, :newPrice)
");
$insertSql = sqlsrv_query($sapconn, $query);
$insertSql->bindParam(":salesRep",$salesRep);
$insertSql->bindParam(":cardName",$cardName);
$insertSql->bindParam(":cardCode",$cardCode);
$insertSql->bindParam(":itemName",$itemName);
$insertSql->bindParam(":itemCode",$itemCode);
$insertSql->bindParam(":itemPrice",$itemPrice);
$insertSql->bindParam(":newPrice",$newPrice);
$salesRep = trim($_POST['salesRep']);
$cardName = trim($_POST['CardName']);
$cardCode = trim($_POST['CardCode']);
$itemName = trim($_POST['ItemName']);
$itemCode = trim($_POST['ItemCode']);
$itemPrice = trim($_POST['Price']);
$newPrice = trim($_POST['requestedPrice']);
$insertSql->execute();
return $insertSql;
}
?>
But the data is not inserting into the database I am fairly new to PHP and this is my first attempt at writing back to the database, so I may be missing something simple, or it may be completely wrong.
Either way all help is appreciated.
EDIT:
My PHP is now this:
if(isset($_POST['submit'])){
//print_r($_POST);
$query = "INSERT INTO PriceRequests (salesRep, CardName, CardCode, ItemName, ItemCode, Price, requestedPrice)
VALUES (:salesRep, :cardName, :cardCode, :itemName, :itemCode, :itemPrice, :newPrice)
";
$stmt = $sapconn->prepare($query);
$salesRep = (isset($_POST['salesRep']) && !empty($_POST['salesRep']))?$_POST['salesRep'] : NULL;
$cardName = (isset($_POST['CardName']) && !empty($_POST['CardName']))?$_POST['CardName'] : NULL;
$cardCode = (isset($_POST['CardCode']) && !empty($_POST['CardCode']))?$_POST['CardCode'] : NULL;
$itemName = (isset($_POST['ItemName']) && !empty($_POST['ItemName']))?$_POST['ItemName'] : NULL;
$itemCode = (isset($_POST['ItemCode']) && !empty($_POST['ItemCode']))?$_POST['ItemCode'] : NULL;
$itemPrice = (isset($_POST['Price']) && !empty($_POST['Price']))?$_POST['Price'] : NULL;
$newPrice = (isset($_POST['requestedPrice']) && !empty($_POST['requestedPrice']))?$_POST['requestedPrice'] : NULL;
$stmt->bindValue(':salesRep', $salesRep, PDO::PARAM_STR);
$stmt->bindValue(':cardName', $cardName, PDO::PARAM_STR);
$stmt->bindValue(':cardCode', $cardCode, PDO::PARAM_STR);
$stmt->bindValue(':itemName', $itemName, PDO::PARAM_STR);
$stmt->bindValue(':itemCode', $itemCode, PDO::PARAM_STR);
$stmt->bindValue(':itemPrice', $itemPrice, PDO::PARAM_STR);
$stmt->bindValue(':newPrice', $newPrice, PDO::PARAM_STR);
$stmt->execute();
return $stmt;
}
But i still have no input to my database and i am getting the following error:
PHP Fatal error: Uncaught Error: Call to a member function prepare() on resource
DB Connection:
<?php
$serverName = "serverName";
$connectionInfo = array( "Database"=>"database_name", "UID"=>"user_Id", "PWD"=>"Password", "ReturnDatesAsStrings"=>true);
$sapconn = sqlsrv_connect( $serverName, $connectionInfo);
?>
One more typo in the PHP code :
$query = prepare("INSERT INTO PriceRequests (salesRep, CardName, CardCode, ItemName, ItemCode, Price, requestedPrice)
VALUES (:salesRep, :cardName, :cardCode, :itemName, itemCode, :itemPrice, :newPrice)
");
The placeholder itemCode does not have the suffix ":".
Check that and try.
Thank you.
UPDATE:
I tried something that you wrote in the question. You have tried to bind the parameters to the placeholders before the parameters are assigned.
When I tried to do so, I got exception. I think this may the reason the data is not getting inserted.
I would suggest you to write the code in the following manner :
PHP CODE :
<?php
if(isset($_POST['submit'])){
print_r($_POST); //Unnecessary, you can remove it
$query = prepare("INSERT INTO PriceRequests (salesRep, CardName, CardCode, ItemName, ItemCode, Price, requestedPrice)
VALUES (:salesRep, :cardName, :cardCode, :itemName, :itemCode, :itemPrice, :newPrice)
");
$insertSql = sqlsrv_query($sapconn, $query);
$salesRep = trim($_POST['salesRep']);
$cardName = trim($_POST['CardName']);
$cardCode = trim($_POST['CardCode']);
$itemName = trim($_POST['ItemName']);
$itemCode = trim($_POST['ItemCode']);
$itemPrice = trim($_POST['Price']);
$newPrice = trim($_POST['requestedPrice']);
$insertSql->bindParam(":salesRep",$salesRep);
$insertSql->bindParam(":cardName",$cardName);
$insertSql->bindParam(":cardCode",$cardCode);
$insertSql->bindParam(":itemName",$itemName);
$insertSql->bindParam(":itemCode",$itemCode);
$insertSql->bindParam(":itemPrice",$itemPrice);
$insertSql->bindParam(":newPrice",$newPrice);
$insertSql->execute();
return $insertSql;
}
?>
I would suggest a few change:
1. As PDO is used here, use a variable to get the Database connection (lets assume its $db_conn).
Instead of
$insertSql = sqlsrv_query($sapconn, $query);
use
$db_conn = new PDO(<connection-string>, <user-name>, <password>);
$stmt = $db_conn->prepare($query)
Then bind the value by :
$stmt->bindValue(<placeholder>, <variable_vlaue>, <value_type>);
eg : $stmt->bindValue(:itemName, $itemName, PDO::PARAM_STR);
Then perform execution:
$stmt->execute();
2. If you place some validation of the data it will be helpful :
Assign the value of POST to the variables via a validation
eg :
$itemName = (isset($_POST['ItemName']) && !empty($_POST['ItemName']))?$_POST['ItemName'] : NULL;
Here, when insert query is executed with 'NULL' it will throw an exception.
N.B. : try-catch block should be used.
I think it should work now.
Please feel free to tell if it does not work, I will check again.
you know there is a typo in the first line? Won't submit with that.
<form actoin="request-new-price.php" method="post" id="demo-form2" data- parsley-validate>
change to form action for a start

How to trigger a sql query by clicking a button in PHP?

so I am trying to make a a online shop , basically what isn't working is to execute a query when the buy clicks the "BUY" button.The query is :
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
and the button is
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
The whole code :
<?php
$id = $_SESSION['SESS_MEMBER_ID'];
include ('config2.php');
$result = mysql_query("select * from shop_vehicule ORDER BY id DESC");
$result2 = mysql_query("select * from accounts where id = '$id'");
while($row = mysql_fetch_array($result2))
$credit = $row['credits'];
while($row = mysql_fetch_array($result)){
$name = $row['nume'];
$price = $row['pret'];
$left = $credit - $price;
$vehid = $row['vehid'];
echo "<p><center><b>$name</b> | $price </center>
More information about $name</p>
<div id=\"toPopup\">
<div class=\"close\"></div>
<span class=\"ecs_tooltip\">Press Esc to close <span class=\"arrow\"></span></span>
<div id=\"popup_content\"> <!--your content start-->
<p>
The $name costs $price, after you'll have $left !</p>
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
</div>
</div>
<div class=\"loader\"></div>
<div id=\"backgroundPopup\"></div>";
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
}
mysql_close();
?>
Here's my attempt to help, I didn't test the codes but it should be working. Please read the comments in the codes. It explains what it does.
$id = $_SESSION['SESS_MEMBER_ID'];
/* To use PDO the following line must be included in your config2.php
define('DB_HOST', 'localhost');
define('DB_NAME', 'database');
define('DB_USER', 'username');
define('DB_PASS', 'password');
$db = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
You can either use define or put the info straight into the PDO() function but I like it when it's easy to read and modify if needed.
*/
include ('config2.php');
$query = $db->prepare("SELECT * FROM accounts WHERE id = :id"); //Please use PDO or MySQLi, MySQL is outdated and unsecure. For this example, I am using my favorite method which is PDO.
$query->execute(array(':id' => $id));
$account = $query->fetchObject(); //Since we only need one line, we're going to use fetchObject object.
$query2 = $db->prepare("SELECT * FROM shop_vehicule ORDER BY id DESC");
$query2->execute();
$vehicules = $query2->fetchAll(); //I am using fetchAll due to multiple row will be returned.
foreach ($vehicules as $row) {
echo '<p><center><b>'.$row['nume'].'</b> | '.$row['pret'].' </center>
More information about $name</p>
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p>The '.$row['nume'].' costs '.$row['pret'].', after you\'ll have '.$account->credit - $row['pret'].' !</p>
BUY
</div>
</div>
<div class="loader"></div>
<div id="backgroundPopup"></div>';
}
// Basically what this part does is whenever the user click on the link, purchase will be set and it'll trigger the query to insert into the vehicule table then return a message if it was successful or not.
if ( isset($_GET['purchase']) ) {
$query = $db->prepare("INSERT INTO vehicles (model,owner) VALUES (':vehid',':id');");
$query->execute(array(':vehid' => $_GET['purchase'], ':id' => $id));
if ($query) {
echo 'Congratulations! You have successfully purchased the vehicule!';
} else {
echo 'An error has occured, the purchase was not complete.';
}
}
Use action=$_SERVER['PHP_SELF'] in the form tag and make a write the MySQL Insert Code in condition where isset($_POST['Buy']) is true.
you can do this in php, but in 2 different files.
The first will have the form, and the second will read the POST value and perform the query
Example(please fill missing pieces)
File 1 . php
<form action="file2.php" method="post">
<input type="hidden" value=<?php echo $vehid;?>" name="vehid">
<input type="hidden" value=<?php echo $id;?>" name="id">
<input type="submit" value="BUY">
</form>
File2.php
$vehid=$_POST['model'];
$id=$_POST['id'];
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
For a complete tutorial see http://www.w3schools.com/php/php_mysql_insert.asp

Cannot pass parameter by reference - MySQLi [duplicate]

This question already has answers here:
PHP error: "Cannot pass parameter 2 by reference"
(2 answers)
Closed 1 year ago.
I have a problem with my insert query. I'm trying to get the user ID from the session variable and insert it into the table along with my other variables that is input via a form.
I have tried printing the $userid variable, and it shows up as 1, which is correct. The bind_param statement just seems to not accept it.
I keep getting this error
Cannot pass parameter 5 by reference in /*** on line 29
Line 29 is the $stmt->bind_param line.
The php code:
<?php
sec_session_start();
if (login_check($mysqli) == true) :
$table = "ticket";
$con = connect($table);
if(isset($_POST['submit'])){
$stmt = $con->prepare('INSERT INTO `ticket` (`subject`, `description`, `assigned`, `status`, `user_id`, `priority_id`, `employee_id`) VALUES (?, ?, ?, ?, ?, ?, ?)');
if (!$stmt) {
throw new Exception($con->error, $con->errno);
}
$userid = $_SESSION['id'];
$stmt->bind_param('sssssss', $_POST['post_subject'], $_POST['post_description'], $_POST['post_assigned'], 'Open', $userid, $_POST['post_priority'], $_POST['post_employee']);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
mysqli_close($con);
}
else{
?>
This is the form:
<?php
$sql = "SELECT * FROM priority";
$result = mysqli_query($con, $sql) or die (mysql_error());
$priority_id='';
while ( $row = mysqli_fetch_array($result)){
$id=$row["id"];
$priority=$row["priority"];
$priority_id.="<OPTION VALUE=\"$id\">".$priority;
}
$sql = "SELECT * FROM members";
$result = mysqli_query($con, $sql) or die (mysql_error());
$assigned_id='';
while ( $row = mysqli_fetch_array($result)){
$id=$row["id"];
$name=$row["name"];
$assigned_id.="<OPTION VALUE=\"$id\">".$name;
}
?>
<div id="ticketSubmit">
<form action="<?php $_PHP_SELF ?>" method="post">
<fieldset>
<legend>Post content</legend>
<div>
<label for="post_subject">
<strong>Choose a subject</strong> for the post
</label>
<input id="post_subject" name="post[title]" type="text">
</div>
<div>
<label for="post_description">
<strong>Supply actual content</strong> for the post
</label>
<textarea id="post_description" name="post[description]"></textarea>
</div>
</fieldset>
<fieldset>
<legend>Post metadata</legend>
<div class="inline">
<label for="post_assigned">
<strong>Choose who assigned</strong> the post
</label>
<select id="post_assigned" name="post[assigned]">
<option> <? echo $assigned_id ?> </option>
</select>
<label for="post_category">
<strong><span style="margin-left:28px">Choose which group</strong> the post is for
</label>
<input id="post_category" name="post[category]" type="text">
<label for="post_priority">
<strong><span style="margin-left:28px">Choose priority</strong> for the post
</label>
<select id="post_priority" name="post[priority]">
<option> <? echo $priority_id ?> </option>
</select>
</div>
</fieldset>
<fieldset>
<legend>Post privacy</legend>
<div class="inline">
<input id="post_allow_comments" name="post[allow_comments]" type="checkbox">
<label for="post_allow_comments">
<strong>Allow comments</strong> on the post
</label>
</div>
<div class="inline">
<input id="post_private" name="post[private]" type="checkbox">
<label for="post_private">
<strong>Make private</strong> so that only friends see it
</label>
</div>
</fieldset>
<p>
<input name = "submit" type="submit" id="submit" value="Submit Ticket">
or
cancel and go back
</p>
</form>
</div>
You can't use 'Open' in your bind_param call. bind_param requires that each parameter is a reference.
You need to store that in a variable first.
$status = 'Open';
$stmt->bind_param('sssssss', $_POST['post_subject'], $_POST['post_description'], $_POST['post_assigned'], $status, $userid, $_POST['post_priority'], $_POST['post_employee']);

Categories