Cannot pass parameter by reference - MySQLi [duplicate] - php

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']);

Related

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";
}
}

prepared statement not inserting data into database

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);
}
}
?>

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

Insert data from one table to another in joined table

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));

Form edit is blanking out my entries

So I've got a form to edit entries which is populating with what has already been entered from the database. When I make an edit, it is saving and redirecting me back to the listing page with no errors, but it's not changing anything. I'm guessing it's getting confused as to where to pull the values from.
This is the the SQL Query to populate the form with the values (this part works):
<?php
// query db
$gigid = $_GET['gigid'];
$con = mysqli_connect("***********","***********","***********","***********");
$result = mysqli_query($con, "SELECT * FROM gigs WHERE gigid=$gigid") or die(mysqli_error());
$row = mysqli_fetch_array($result);
mysqli_close($con);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$gig_name = $row['gig_name'];
$gig_type = $row['gig_type'];
$gig_date = $row['gig_date'];
$gig_customer = $row['gig_customer'];
$gig_venue = $row['venue_name'];
$gig_fee = $row['gig_fee'];
$gig_status = $row['gig_status'];
}
?>
This is an excerpt from the form:
<form class="form-horizontal" id="create-ticket" method='post' action='edit_gig_process.php? gigid=<?php echo $_GET['gigid']; ?>'>
<fieldset>
<legend>Edit Gig Information</legend>
<input type="hidden" class="input-xxlarge" id="gig_date_created" name="gig_date_created">
<input type="hidden" class="input-xxlarge" id="userid" name="userid">
<div class="control-group">
<label class="control-label" for="gigid">Gig ID</label>
<div class="controls">
<input type="text" name="gigid" disabled="disabled" value="<?php echo $_GET['gigid']; ?>" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="gig_name">Gig Name (Required)</label>
<div class="controls">
<input type="text" class="input-xxlarge" id="gig_name" value="<?php echo $row['gig_name']; ?>" name="gig_name">
</div>
</div>
This is an excerpt from the update query:
$gigid = $_GET['gigid'];
$sql= "UPDATE gigs set
gig_name='$gig_name',
gig_type='$gig_type',
gig_customer='$gig_customer',
gig_date='$gig_date_created',
gig_start_time='$gig_start_time',
gig_end_time='$gig_end_time',
gig_fee='$gig_fee',
gig_status='$gig_status',
venue_name='$venue_name',
venue_address='$venue_address',
venue_contact='$venue_contact',
WHERE
gigid='$gigid'";
header('Location: http://managegigs.com/cp/my-gigs.php');
mysqli_close($con);
You are not running a update query, your update is just a string.
After
$sql= "UPDATE gigs set
gig_name='$gig_name',
gig_type='$gig_type',
gig_customer='$gig_customer',
gig_date='$gig_date_created',
gig_start_time='$gig_start_time',
gig_end_time='$gig_end_time',
gig_fee='$gig_fee',
gig_status='$gig_status',
venue_name='$venue_name',
venue_address='$venue_address',
venue_contact='$venue_contact'
WHERE
gigid='$gigid'";
add:
mysqli_query($con,$sql);
also, at least change this:
$gigid = $_GET['gigid'];
add:
$gigid = mysqli_real_escape_string($gigid);
directly after to have it a little secured. Putting $_GET directly to DB is dangerous.
Uploadpart in complete:
$gig_name = $_POST['gig_name'];
// fetch all $_POST(ed) data
// and secure with
$gig_name = mysqli_real_escape_string($con,$gig_name);
$gigid = $_GET['gigid'];
$gigid = mysqli_real_escape_string($con,$gigid);
$sql= "UPDATE gigs set
gig_name='$gig_name',
gig_type='$gig_type',
gig_customer='$gig_customer',
gig_date='$gig_date_created',
gig_start_time='$gig_start_time',
gig_end_time='$gig_end_time',
gig_fee='$gig_fee',
gig_status='$gig_status',
venue_name='$venue_name',
venue_address='$venue_address',
venue_contact='$venue_contact'
WHERE
gigid='$gigid'";
mysqli_query($con,$sql);
header('Location: http://managegigs.com/cp/my-gigs.php');
mysqli_close($con);

Categories