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
Related
My prepared statements for inserting data into a database are not working. I have had these issues accross the board but I am including one example just incase I am making a simple mistake. The query is running ok as I am getting a message which I placed myself within the code, however nothing is being entered into the actual database. MY issues so far with prepared statements is the lack of feedback you get when something isnt working. Any help would be greatly appreciated.
<?php
if(isset($_POST['newsubject'])){
include('../connection/conn.php');
//Prepare the insert statement
$insertquery = "INSERT INTO miiLearning_Tutors(tutor_id,subject_level,
price, subjects) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($conn, $insertquery)){
//bind variable to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iidi", $newtutor, $newsubject,
$newlevel, $newprice);
//Set Values
$newtutor = $_POST["tutorId"];
$newsubject = $_POST["subjects"];
$newlevel = $_POST["subjectlevel"];
$newprice = $_POST["price"];
mysqli_stmt_execute($stmt);
echo"<p>Query Ran</p>";
} else{
echo "ERROR: Could not prepare query: $query . " .mysqli_error($conn);
}
}
?>
HTML for form:
<form enctype="multipart/form-data" action='updatesubjects.php' method="post" id="update-subjects-form" name="new-subject" >
<fieldset>
<!--Tutor ID (Posted from previous page) -->
<input type="hidden" name="tutorId" value='<?php echo "$userarray[0]";?>'>
<!-- Subject -->
<div class="form-group">
<label for="subjects">Subject</label>
<select name="subjects" type="text" class="form-control">
<?php
if(mysqli_num_rows($subjectsresult)>0){
while($row = mysqli_fetch_assoc($subjectsresult)){
$get_subjectid = $row['subject_id'];
$get_subjectname = $row['subject'];
echo "<option value='$get_subjectid'>$get_subjectname</option>";
}
}
?>
</select>
</div>
<!-- Level -->
<div class="form-group">
<label for="subjectlevel">Subject Level</label>
<select name="subjectlevel" type="text" class="form-control">
<?php
if(mysqli_num_rows($levelresult) > 0){
while($row = mysqli_fetch_assoc($levelresult)){
$get_levelid = $row['level_id'];
$get_namelevel = $row['level'];
echo "<option value='$get_levelid'>$get_namelevel</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<label for="subjectlevel">Price</label>
<input type='number' step='0.01' min='0' name='price'>
</div>
<button class="btn btn-primary" type="submit" name="newsubject" id="bookingsform">Submit form</button>
</fieldset>
</form>
I apologies for any poor indentation
You need to declare your variables and assign value to them before binding. At the moment you should have undefined variables.
On development environment ensure error reporting is on.
<?php
error_reporting(-1);
ini_set('display_errors', 1);
if(isset($_POST['newsubject'])){
include('../connection/conn.php');
//Set Values
$newtutor = $_POST["tutorId"];
$newsubject = $_POST["subjects"];
$newlevel = $_POST["subjectlevel"];
$newprice = $_POST["price"];
//Prepare the insert statement
$insertquery = "INSERT INTO miiLearning_Tutors(tutor_id,subject_level, price, subjects) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($conn, $insertquery)){
//bind variable to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iidi", $newtutor, $newsubject, $newlevel, $newprice);
mysqli_stmt_execute($stmt);
echo"<p>Query Ran</p>";
} else{
echo "ERROR: Could not prepare query: $query . " .mysqli_error($conn);
}
}
?>
I am trying to do a simple edit/update of my data in the database. But somehow it will not work.
So I am able to read out the saved data into the form. I also don't have any errors
I have stared at my code and googled for hours but I don't see where I might have made a mistake with my code.
The printed echo gives the following output which seems to be right:
HTML code:
<form id="formAddCategory" class="FrmCat" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group">
<!-- hidden id from tbl -->
<input type="hidden" name="hiddenId" value="<?php echo $hiddenID ?>" />
<label for="recipient-name" class="control-label">Category Name:</label>
<input type="text" class="form-control" id="recipient-name1" name="category" required="" value="<?php echo $category ?>" />
</div>
<button type="submit" id="btnEditCat" class="btn btn-danger" name="editCategory">Save Category</button>
</form>
Part of my php code to edit/update:
<?php
//edit/update data to db
if(isset($_POST['editCategory'])){
$categoryUpdate = mysqli_real_escape_string($con, $_POST['category']);
$categoryID = mysqli_real_escape_string($con, $_POST['hiddenId']);
$qry = "UPDATE tbl_Category SET category = $categoryUpdate WHERE category_id = $categoryID";
$result = mysqli_query($con, $qry);
echo $qry;
if($result){
header("Location: category.php");
}
}
?>
You need single quote ' to wrap your parameter:
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";
You should use single quotes (') for values
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";
Also you can use like this to avoid SQL injection (See here)
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
I am trying to insert 4 forms that are the same. but with different values to mysql using PHP.
When I submit my data, the database only takes the values from the last form and inserts it 4 times. I am trying to get the values from all 4 on submit.
<div class="req3">
<h1>Requirement 4</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<br>
Enter info for 4 teams and it will inserted into the database<br><br>
<div class="sqlForm">
<p class="formHead">Team 1</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 2</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 3</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 4</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br><br></div>
<input class="styled-button" type="submit" name="insert" value="Submit">
</form>
<?php
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
$servername = "localhost:3306";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo ("Connection failed: " . $conn->connect_error);
} else {
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite')";
if ($conn->multi_query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysql_query($sql);
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
}
}
?>
chnage the names of your controls so they Post as Arrays
<input type="text" name="teamname[G1]">
<input type="text" name="teamname[G2]">
this why when you use $varTname = $_POST['teamname']; $varTname is an array and each of the 4 values of teamname are set as $varTname['G#'] where # matches the number you set for that group of input fields.
then use a for loop to get the data and execute your query, something like bellow. while you at it you can also fix up your SQL Injection vulnerability. you may also want to so some more sanitation to the data just to be sure
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$stmt = $mysqli->prepare('INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES (?,?,?,?,?,?)');
$varTname1Bind = "";
$varTnameBind = "";
$varCityBind = "";
$varBplayerBind = "";
$varWebsiteBind = "";
// assuming they are all strings, adjust where needed
$stmt->bind_param('sssssss',
$varTname1Bind,
$varTnameBind,
$varCityBind,
$varBplayerBind,
$varYearformedBind,
$varWebsiteBind);
for($i = 1; i < 5; $i++)
{
$varTname1Bind = $varTname['G'.$i];
$varTnameBind = $varTname['G'.$i];
$varCityBind = $varCity['G'.$i];
$varBplayerBind = $varBplayer['G'.$i];
$varYearformedBind = $varYearformed['G'.$i];
$varWebsiteBind = $varWebsite['G'.$i];
$stmt->execute();
}
will save you on how much code you need to do
You can convert your input names into arrays by adding [] then in your php loop through the array of the $_POST[] and built up your $sql by concatenating the values until you finish looping through all values and INSERT it as multiple values.
HTML:
<label>Team Name:</label> <input type="text" name="teamname[]"><br>
<label>City:</label> <input type="text" name="city[]"><br>
<label>Best Player:</label> <input type="text" name="bestplayer[]"><br>
<label>Year Formed:</label> <input type="text" name="yearformed[]"><br>
<label>Website:</label> <input type="text" name="website[]"><br>
PHP:
<?php
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES ";
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$sql .= "(" .$varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite. "),";
}
$sql = rtrim($sql, ','); // omit the last comma
// Then Excute your query
?>
This way you don't need to give them unique names name="test1", name="test2" and so, to see it in action check this PHP Fiddle in the bottom of the result page, I've already set the values of the input fields, just hit submit and go to the bottom of the result page to see the composed INSERT statement.
NOTE that the above SQL is just a demo on how to build it up, DO NOT use it like this without validation and sanitizing.. ALSO STOP querying this way and instead use Prepared Statements with PDO or MySQLi to avoid SQL Injection.
So for MySQLi prepared statements, procedural style - I work with PDO - as you see in this PHP Fiddle 2, the code is:
<?php
// you validation goes here
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
// enter your credentials below and uncomment it to connect
//$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES";
$s = '';
$bind = '';
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$sql .= " (?, ?, ?, ?, ?)";
$s .= 's';
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$bind .= " , " . $varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite;
}
$sql = rtrim($sql, ','); // omit the last comma
$s = "'" .$s. "'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, $s , $bind);
mysqli_stmt_execute($stmt);
}
?>
Normally this is done by creating arrays of form controller.
<input type="text" name="teamname[]">
<input type="text" name="city[]">
And then you can get an array in post request.
Hope this helps!
use different name like teamname1,teamname2,teamname3,teamname4
<input type="text" name="teamname1">
<input type="text" name="teamname2">
<input type="text" name="teamname3">
<input type="text" name="teamname4">
For get values :-
$varTname1 = $_POST['teamname1'];
$varTname2 = $_POST['teamname2'];
$varTname3 = $_POST['teamname3'];
$varTname4 = $_POST['teamname4'];
For insert values :-.
$sql = "INSERT INTO Teams (teamname)
VALUES ('$varTname1'),
('$varTname2'),
('$varTname3'),
('$varTname4')
or you can try this:-
<input type="text" name="teamname[]">
Get value like :-
$_POST['teamname'][0]
try this method
$sql = "INSERT INTO Teams (teamname, city, bestplayer,yearformed,website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
";
$sql.= query same as abov
$sql.= query same as abov
$sql.= query same as abov
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
note the . dot after the first query.
I think you should also use an auto increment keyThis should work.
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));
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']);