Search & Update table using 2 variables - mysqli

Please help me out with this. I am learning using w3s & stackoverflow support which I really appreciate.
I am learning MySQLi now. I was able to set up table on wamp server. The table has 5 columns for UserId, Password, Telephone, email and Program.
The 1st time a user logs on, the userid & password are inserted in the table. This works fine. The user is free to log out & return later to continue.
Next, the user provides Telephone, email & program info. The task now is to search the table for this user using the UserId & Password provided to update the Telephone, email and Program columns. I have problem achieving this. Below my doc, syntax etc.
<form method="post" action="stackhelpupdate.php">
<b>User Id:<b><br>
<input name="userid" type="text" required pattern="[A-Za-z0-9.-_]{5,10}">
<br>
<b>Password:<b><br>
<input name="userpswd" type="password" required pattern="[A-Za-z0-9&*]
{8,20}"><br>
<b>Telephone* </b><br>
<input type="text" name='myfone' required pattern="[0-9+]{5,15}"><br>
<b>e-mail Address*<b><br>
<input type="email" name='myemail' required pattern="[A-Za-z0-9#.-_]{5,30}">
<br>
<b>Program* </b><br>
<input type="text" name='myprog' pattern="[A-Za-z0-9]{3,10}"><br>
<p><b><i>Review all your inputs above. When you are satisfied, click
Submit</p></b></i>
<input id="submit" type="submit" value="Submit">
</form>
This form successfully post to stackhelpupdate.php which is like this:
<table id="usercontact">
<tbody>
<tr>
<th class="hdr">Telephone</td>
<td><input type="text" name='myfone' readonly value="<?php echo $myfone;?>">
</td>
</tr>
<tr>
<th class="hdr">email</td>
<td><input type="text" name='myemail' readonly value="<?php echo $myemail;?
>"></td>
</tr>
<tr>
<th class="hdr">Program</td>
<td><input type="text" name='myprog' readonly value="<?php echo $myprog;?>">
</td>
</tr>
</tbody>
</table>
<br>
<form action="next.php" method="post">
<input id='submit' type="submit" value="Next">
Note that I have structured this way for learning purpose only. Code for server end is this:
<?php
$servername = "localhost";
$username = "user";
$password = "hellosir";
$dbname = "mydB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$userid = test_input($_POST["userid"]);
$userpswd = test_input($_POST["userpswd"]);
$myfone = test_input($_POST["myfone"]);
$myemail = test_input($_POST["myemail"]);
$myprog = test_input($_POST["myprog"]);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql="UPDATE `mytbl` SET `Telephone`=".$_POST['myfone'].",`email`=".$_POST['myemail'].",`Program`=".$_POST['myprog']." WHERE `UserId`=.$userid. AND `Password`=.$userpswd.";
if (mysqli_query($conn, $sql)) {
echo "User data saved successfully";
} else {
echo "Error saving your data " . mysqli_error($conn);
}
mysqli_close($conn);
?>
I got the following error:
Error saving usercontact data You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the right
syntax to use near `Telephone`=0802301' at line 1
I have also tried Prepared Statement below which also failed:
$conn->query("update mytbl SET Telephone = ?, email = ?, Program = ? WHERE
UserId = ? AND Password = ?");
$conn->bindParam("sssss", $myfone, $myemail, $myprog, $userid, $userpswd);
$conn->execute();
I got the error:
Fatal error: Call to undefined method mysqli::bindParam() in
C:\wamp\www\stackhelpupdate.php on line 66
1.
Please help me identify my errors.
2.
I think my major problem is the insufficient examples in w3s. Any other useful sites for PHP & SQL.
3.
Apart from PHP, is there a javascript method to work also on tables in database.
Appreciate all efforts.

Your prepared statement codes are wrong. Please look at following example.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
You need to cover your codes as follow.
$conn->prepare("update mytbl SET Telephone = ?, email = ?, Program = ? WHERE
UserId = ? AND Password = ?");
$conn->bind_param("sssss", $myfone, $myemail, $myprog, $userid, $userpswd);
$conn->execute();

The Prepared statement below works fine:
$stmt = $conn->prepare("update mytbl SET Telephone = ?, email = ?, Program =
? WHERE UserId = ? AND Password = ?");
$stmt->bind_param("sssss", $myfone, $myemail, $myprog, $userid, $userpswd);
$stmt->execute();

Related

PDO prepaired statement UPDATE not working

I've been persistently trying to get this statement to update my db, but with no success. I have a form that is to allow user to update their username and email. What am I overlooking?
Here is my statement:
<?php require_once('config.php');
$id= $_SESSION['id'];//get user id you can use session also
if (isset($_POST['submit'])){
$username = $_POST['username'];
$email = $_POST['email'];
$query = "UPDATE members SET username = :username ,email = :email WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':username',$username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
}
$query = "SELECT * FROM members WHERE id = $id"; //Get user info
$stmt = $db->prepare($query);
$stmt ->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
// output data of each row
foreach($result as $row){
$username = $row['username'];
$email = $row['email'];
}
}
?>
Here is my form:
<form role="form" class="cf-form floating-labels" method="post" action="<?php filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?>">
<fieldset>
<legend>My Account<br />
<img class="logo_contact" src="img/jobmiser_logo2.png" alt="jobmiser logo" />
</legend>
<div class="icon">
<label class="cf-label" for="username">Username</label>
<input class="user" type="text" name="username" id="username" value="<?php echo $username ?>" tabindex="2" required />
</div>
<div class="icon">
<label class="cf-label" for="email">Email</label>
<input class="email" type="email" name="email" id="email" value="<?php echo $email ?>" tabindex="3" required />
</div>
</fieldset>
<fieldset>
<div class="icon">
<input name="submit" type="submit" value="Update" />
</div>
</fieldset>
</form>
You need to bind the :id parameter in your update query:
// bind :id
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
// You also need to execute it
$stmt ->execute();
In the second statement you should also bind the value id and not insert it directly into the string.
// BAD
$query = "SELECT * FROM members WHERE id = $id";
// GOOD
$query = "SELECT * FROM members WHERE id = :id"; //Get user info
$stmt = $db->prepare($query);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt ->execute();

registration script keeps showing errors when all fields are filled

Im having a little issue with my registration script.
I am trying to add rows into my mysql database.
This is my form verifier to make sure all fields are filled:
//Variables from the table
$user = $_POST['un'];
$pass = $_POST['pw'];
$rpass = $_POST['rpw'];
//Prevent MySQL Injections
$user = stripslashes($user);
$pass = stripslashes($pass);
$rpass = stripslashes($rpass);
$user = mysqli_real_escape_string($user);
$pass = mysqli_real_escape_string($pass);
$rpass = mysqli_real_escape_string($rpass);
//Check to see if the user left any space empty!
if($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill in all the information!";
}
and this is the form
<form action="register_proc.php" method="post">
<label for="un">Username</label>
<input type="text" name="un" id="un" placeholder="username"/>
<br/>
<label for="pw">Password</label>
<input type="password" name="pw" id="pw" placeholder="password"/>
<br/>
<label for="rpw">Repeat Password</label>
<input type="password" name="rpw" id="rpw" placeholder="repeat password"/>
<br/>
<input type="submit" name="submit" value="Complete Registration"><br>
<div style="float: left;">
Home
</div>
<div style="float: right;">
Login
</div>
</form>
I have no idea why it keeps outputting the else statment "Please fill in all the information!"
All of the $post variables have the correct names
thank you for the upcoming support.

Form data being posted but not being sent with php mail()

I am creating a job application form which has a drop down box that the user can select a city from and continue filling out the form. The objective here is depending on what city the user selected and then submits the form, it will be sent to an email address assigned to the value of that option. I have successfully been able to make this work on just simple form fields like "Name, email, and message". However since I have actually started creating the form and many more form fields it is no longer working. I have worked with a couple of tests, one using print_r($_POST);. After submitting the form it will display all of the form values that was sent, but not mail those results using mail() function. php code is below:
<?php
//Sanatize field inputs
if(isset($_POST['post'])) {
// check reCAPTCHA information
require_once('recaptchalib.php');
$privatekey = "6LcuhsgSAAAAAJ1Xlct4dmqOT2SnlhOuwAEImAXH ";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
// if CAPTCHA is correctly entered!
if ($resp->is_valid) {
$headers = "From: $email\r\n";
$headers = "Reply-To: $email\r\n";
$headers = "MIME-Version: 1.0\r\n";
$headers = "subject: Application\r\n";
$headers = "Content-Type: text/html; charset=utf-8\r\n";
$cities = $_POST['cities'];
$lastname = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$middle = filter_var($_POST['middle'], FILTER_SANITIZE_STRING);
$street = filter_var($_POST['street'], FILTER_SANITIZE_STRING);
$city = filter_var($_POST['city'], FILTER_SANITIZE_STRING);
$state = filter_var($_POST['state'], FILTER_SANITIZE_STRING);
$zip = filter_var($_POST['zip'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$hphone = filter_var($_POST['hphone'], FILTER_SANITIZE_STRING);
$cphone = filter_var($_POST['cphone'], FILTER_SANITIZE_STRING);
$social = filter_var($_POST['social'], FILTER_SANITIZE_STRING);
$referral = filter_var($_POST['referral'], FILTER_SANITIZE_STRING);
$position = filter_var($_POST['position'], FILTER_SANITIZE_STRING);
$pay = filter_var($_POST['pay'], FILTER_SANITIZE_STRING);
$message = "
New mail from:<br><br>
Name: $firstname $lastname <br>
Email: $email <br>
Message: $position <br >
$pay";
//$to = "testing#website.com";
//Here I provide the email address for cities
$email1 = "testin1g#website.com";
$email2 = "testing2#website.com";
$email3 = "testing3#website.com";
//print_r($_POST);
// Logic for getting the value of drop down and then sending mail.
if ($cities == "NY"){
$sendMail = mail($email1, $message, $headers);
if($sendMail) {
echo 'Thank you ' .$firstname. ', the mail has been successfully sent!<br><br>';
} else {
echo 'An error occured and the mail could not be sent.<br>
Please try again later.';
}
}
elseif ($cities == "NC"){
$sendMail = mail($email2, $message, $headers);
if($sendMail) {
echo 'Thank you ' .$firstname. ', the mail has been successfully sent!<br><br>';
} else {
echo 'An error occured and the mail could not be sent.<br>
Please try again later.';
}
} elseif ($cities == "TX"){
$sendMail = mail($email3, $message, $headers);
if($sendMail) {
echo 'Thank you ' .$firstname. ', the mail has been successfully sent!<br><br>';
} else {
echo 'An error occured and the mail could not be sent.<br>
Please try again later.';
}
} elseif ($cities == "ME"){
$sendMail = mail($email1, $message, $headers);
if($sendMail) {
echo 'Thank you ' .$firstname. ', the mail has been successfully sent!<br><br>';
} else {
echo 'An error occured and the mail could not be sent.<br>
Please try again later.';
}
}
} else {
// handle the CAPTCHA being entered incorrectly
echo 'You Did not enter the CAPTCHA in correctly. Please go back and do so.';
}
}
session_destroy();
?>
As you can see above I have a couple of email addresses listed and then using the if statement I am telling php if the "cities = state" to send to that email address. However this is the part it is getting hung up on. It is going straight to my error message.
And my html form:
<form method="post" action="../sendemail.php">
<table cellpadding="0" cellspacing="0" width="900">
<tr>
<td width="800" bgcolor="White">
<div id="copyContainerwide">
<h1>NexxLinx Career Opportunities</h1>
<p>
Thank you for your interest in a career with NexxLinx! We have many different opportunities for employment, which may vary depending
upon which center you are interested in applying for. For more information on what positions we have available, please contact your local
NexxLinx centers, or visit us in person! </p>
<br/>
<p>To apply please select the center you would like to apply to:</p>
<select name="cities">
<option value="NY">Newburgh, NY</option>
<option value="NC">Jacksonville, NC</option>
<option value="TX" >Austin, TX</option>
<option value="ME">Orono, ME</option>
<option value="UT">South Jordan, UT</option>
</select>
<br/>
<p> TO THE APPLICANT: You must fully complete this application for it to be considered. Applications are active for ninety (90) days;
thereafter, you must personally renew the application to be considered for employment. We provide equal opportunities to all applicants
and employees without regard to race, color, religion, sex, national origin, age, or disability, in accordance with applicable federal
and state laws. Accommodation is available to applicants with a disabling condition, when applying, testing, or interviewing for a position.
Please contact the Human Resource Department to request accommodation.</p>
<fieldset>
<legend>General Information </legend>
<table>
<tr>
<td>Last Name:<br/>
<input name="lastname" type="text" size="30" /></td>
<td> First Name:<br/>
<input name="firstname" type="text" size="30"/></td>
<td> Middle Name:<br/>
<input name="middle" type="text" size="30"/></td>
</tr>
</table>
<table>
<tr>
<td>Street Address<br/>
<input name="street" type="text" size="50" /></td>
<td> City<br/>
<input name="city" type="text" size="30" /></td>
<td>State (abbr.)<br/>
<input name="state" type="text" size="7" /></td>
<td> Zip Code <br/>
<input name="zip" type="text" size="12" /></td>
</tr>
</table>
<table>
<tr>
<td>E-mail:<br/>
<input name="email" type="email" size="50" /></td>
<td>Home Phone:<br/>
<input name="hphone" type="tel" size="15" /></td>
<td>Cell Phone:<br/>
<input name="cphone" type="tel" size="15" /></td>
<td>Social Security Number<br/>
<input name="social" type="text" size="12" /></td>
</tr>
</table>
<table>
<tr>
<td>Referred By:</td>
<td><input name="agency" type="checkbox" />Agency</td>
<td><input name="advert" type="checkbox" />Advertisement</td>
<td><input name="employee" type="checkbox" />Empoloyee</td>
<td><input name="other" type="checkbox" />Other</td>
</tr>
<table>
<tr>
<td>Please list the name of the above agency, publication with the advertisement, employee, or other referall.<br/>
<input name="referral" type="text" size="60" /></td>
</tr>
</table>
<table>
<tr>
<td>Position Applied For:<br/>
<input name="position" type="text" size="50"/></td>
<td>Pay Desired:<br/>
$<input name="pay" type="text" size="20" /></td>
</tr>
<tr>
<td>
<?php
require_once('../recaptchalib.php');
$publickey = "6LcuhsgSAAAAAHtXF5i5f5XEAZmjyAtYvHGGQlhf ";
echo recaptcha_get_html($publickey);
?>
</td>
</tr>
<tr>
<td>
<input type="submit" name="post" value="submit" />
</table>
</fieldset>
</div>
</td>
</tr>
</table>
</form>
Thanks for any advice you can give me!
UPDATE:
Finally have this working! Thank you everyone for the help. For what ever reason and please correct if this is not right, I moved my headers up at the top of all of my other variables and it now works like a charm. FYI: I was working on this locally with WAMP and had a dumby sendmail configured to send through my gmail account. It work with very simple forms but apparently this one was a little too advanced, so I finally uploaded and finished testing it on my live server.
Something extra that maybe someone can help me with is validating a social security number and show the * when someone inters in numbers. Can that be done with javascript?
why not assign the email address to the value of the area if you can always reverse if your going to insert it in the database it like
<select name="cities">
<option value="test1#yahoo.com">Newburgh, NY</option>
<option value="test2#yahoo.com">Jacksonville, NC</option>
<option value="test3#yahoo.com" >Austin, TX</option>
</select>
$to=$_POST['cities'];
mail('$to', '$subject', '$message);
if you need to insert the location in database just reverse it
if($citiies==test1#yahoo.com)
{
//insert into database NY
}
this code is shorter and looks cleaner but you will need to if else it again if your going to store the
location in the database
it will be shorter because you will not compare values just send it to what the value assign is

Codeigniter - update table from form with checkbox

I'm trying to update a MySQL table with Codeigniter.
My model code is:
function update_customer_records($updatedrow)
{
$this->db->where('id',$this->input->post('id'));
$this->db->update('customers',$updatedrow);
}
My view is:
$attributes=array(
'name'=>'updatecustomer',
'id'=>'updatecustomer',
);
echo form_open('masterdata/manage_customers',$attributes);
?>
<table>
<tr>
<td> </td><td> </td><td>Customer Name</td><td>postalcode</td>
<tr>
<?php if(isset($records)) : foreach ($records as $row) : ?>
<tr>
<td>
<?php echo anchor('masterdata/customers_updated/'.$row->id, img(array('src'=>'images/delete_icon.png','border'=>'0','alt'=>'Delete'))); ?>
</td>
<td>
<input type=checkbox name="editcustomer[]" id="editcustomer[]" value="<?php echo $row->id ?>">
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->customer_name ; ?>" >
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->postalcode ; ?>" >
</td>
</tr>
<?php endforeach ; ?>
</table>
<input type="submit" value="Update Selected">
<?php else : ?>
<h2> No Records Found</h2>
<?php endif; ?>
<?php echo form_close(); ?>
My controller is :
function manage_customers()
{
$data['title']="Manage Customers";
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_records()){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_manage_customers",$data);
$this->load->view("master_data/view_master_data_footer");
$editcustomer = $this->input->post('editcustomer');
if(isset($editcustomer)){
//begin outputting id of selected checkbox
foreach ($editcustomer as $row) :
echo $row;
$updatedrow=array(
'id'=>$row,
'postalcode'=>'44444'
);
$this->model_master_data->update_customer_records($updatedrow);
endforeach;
}
I have two issues :
How do I stop the foreach from running if a checkbox has not been checked.
How do I pass the array to the model correctly so that the update runs?
Thanks in advance as always.
First of all I found two fields in the form with the same name and id (given below) and in one field you are setting it's value customer_name and in another you are setting postalcode.
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->customer_name ; ?>" >
--^^--
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->postalcode ; ?>" >
--^^--
</td>
So I think (probably) the name and id of the second field should be postalcode according to it's value.
Also you don't need to worry about foreach loop because the code inside the loop ll run only if there are checked check boxes on the form because unchecked check boxes won't be submitted but you can check and run the loop using following code
if( $this->input->post('editcustomer') != false )
{
foreach ($editcustomer as $row)
{
// code here
}
}
The if condition will return false if the editcustomer is not found or not submitted with the form. Also there is no id field in your form and in this case you can't use $this->input->post('id'), so if you need to check the check box id in the where clause of your model then you can use
In The controller :
if( $this->input->post('editcustomer') != false )
{
$this->load->model('model_master_data');
foreach ($editcustomer as $row_id)
{
$data = array( 'postalcode' => '44444' );
$this->model_master_data->update_customer_records( $row_id, $data );
}
}
I don't think you need to pass 'id'=>$row, because you probably don't wan't to update this field. Also you should use form validation to check the form input before updating the record (you may set the postcode field required to bound the user to enter a postcode).
In The Model :
function update_customer_records( $id, $data )
{
$this->db->where( 'id', $id );
$this->db->update( 'customers', $data );
}
So it'll do something like this (pseudo code)
update the customers table set `postalcode` = '44444' where `id` = $id
Update :
I think you can also use the update_batch.
In The controller :
if( $this->input->post('editcustomer') != false )
{
$data = array();
foreach ($editcustomer as $row_id)
{
$data[] = array( 'id' => $row_id, 'postalcode' => '44444';
}
$this->load->model('model_master_data');
$this->model_master_data->update_customer_records( $data );
}
In The Model :
function update_customer_records( $data )
{
$this->db->update_batch('customers', $data, 'id');
}
Duplicate topic with "Codeigniter update mysql table from form with CI" ?
how do I stop the foreach from running if a checkbox has not been checked.
You don't have to stop the foreach from running if a checkbox has not been checked.
Because $editcustomer variable only contain checkbox checked.
How do I pass the array to the model correctly so that the update runs?
Your model is wrong. It should be:
public function update_customer_records($updatedrow)
{
$this->db->update('customers', $updatedrow);
}
You don't need to write $this->db->where('id',$this->input->post('id')); (and it's wrong, because you can't use $this->input->post() in your model) because you already pass id in $updaterow.
Edit : I'm sorry, I read your code too quickly!
function update_customer_records($updatedrow)
{
$this->db->where('id',$this->input->post('id'));
$this->db->update('customers',$updatedrow);
}
...is correct. Alternatively, you can write it in a shorter way:
function update_customer_records($updatedrow)
{
$this->db->update('customers', $updatedrow, array('id' => $this->input->post('id')));
}

Receiving data from a form and modificating it using preg_replace

I have the following HTML code:
<form method="post" action="">
<b>Name: <input type="text" name="username" size="20" />
<input type="submit" value="Login" name="login" />
</form>
and:
<?php
if(isset($_POST['login'])){
$check = $_POST['username'];
?>
Whenever a user submits his username, the user should receive his username back but with the following modifications:
1) *Sapce bars will be replaced with "_"
2) *All letters will become non-capital letters.
Example:
Username: "I Like Icecream"
Result:
i_like_icecream
The message should be displayed to the user as an variable through an echo.
echo "$result";
I was thinking about doing it with preg_repalce, but didn't really manage to since I am not familiar with it very well. Any help will be appriciated.
preg_replace() is way too powerful but way expensive for this task. The patterns you need to change are constant, so you're better of using str_replace() and mb_strtolower()
$encoding = 'UTF-8'; // optional
$name = $_POST['usernamename']
$name = str_replace(' ', '_', $name);
$name = mb_strtolower($name, $encoding); // or $name = mb_strtolower($name); if you don't specify encoding