MySQL Updating database error - mysql

Im trying to get it so when you press a button it updates the value of 'subscribe' to 1 but for some reason its not working.
<?php
session_start();
$userid = $_SESSION['userID'];
$username = $_SESSION['username'];
require '../../core/connect.php';
if ($_SESSION['userID']) {
if (isset($_POST['subscribe'])) {
$query2 = mysql_query("UPDATE `users` SET `subscribe`='1' WHERE `username`='".$username."'") or die(mysql_error());
if ($query2) {
header("Location: /index.php");
} else {
echo "An error occured. Your subscription failed! Please try again later.";
}
}else {
echo "Error occured.";
}
}else {
echo "No session found.";
}
?>
The error im getting is the 'Error occured.'
The field is an int with the default value as 0
Thanks!

'Error Occurred' implies
if(isset($_POST['subscribe'])) // is evaluating to false
use
print_r($_POST) // and post the result

if(isset($_SESSION['subscribe']))

Related

Adding data to ENUM field via form in sql

I currently have a form where values are submitted to add data to my table. I have a field 'property_id' which is an ENUM. Every time I try to submit the field I get the error message:
Fatal error: Uncaught mysqli_sql_exception: Data truncated for column 'property_id' at row 1 in ...
Is there any way I can add data to the ENUM field via my form? Here is my code below that connects the form to the database:
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$property_id = filter_input(INPUT_POST, 'property_id');
$firstline_address = filter_input(INPUT_POST, 'firstline_address');
$postcode = filter_input(INPUT_POST, 'postcode');
$vacant = filter_input(INPUT_POST, 'vacant');
if (!empty($property_id)) {
if (!empty($postcode)) {
$host = "";
$dbusername = "";
$dbpassword = "";
$dbname = "";
//new connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ')'
. mysqli_connect_error());
} else {
$sql = "INSERT INTO property (property_id, firstline_address, postcode, vacant)
values ('$property_id', '$firstline_address', '$postcode', '$vacant')";
if ($conn->query($sql)) {
echo "New property has been successfully added. Refresh page to view new property in the table below.";
} else {
echo "Error: ";
//. $sql ."<br>".$conn->error;
}
$conn->close();
}
} else {
echo "All fields are required!";
die();
}
} else {
echo "Please fill out all fields to continue.";
die();
}

Yii2 swiftmailer foreach multiple email

I want to run a code to send email to all users. At first i used this code to run a test.
->setTo([
'john.doe#gmail.com' => 'John Doe',
'jane.doe#gmail.com' => 'Jane Doe',
])
I found out that the mail is 1 mail sent to multiple recipents, while i need to 2 emails to 2 recipients. Because in reality i need to send to over hundred people at once. SO i try foreach loop.
public function contact($email)
{
$users = Users::find()->all();
$content = $this->body;
foreach($users as $user){
if ($this->validate()) {
Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
->setTo($user->email)
->setFrom($email)
->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
->setTextBody($this->body)
->send();
return true;
}
}
return false;
}
But it only run 1 loop and end.
Please tell me where i'm wrong.
Thank you
the reason just one mail is sent is the
return true
it returns after the first email is sent, you should use try{}catch(){} like below
public function contact($email) {
$users = Users::find()->all();
$content = $this->body;
try {
foreach ($users as $user) {
if ($this->validate()) {
$r = Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
->setTo($user->email)
->setFrom($email)
->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
->setTextBody($this->body)
->send();
if (!$r) {
throw new \Exception('Error sending the email to '.$user->email);
}
}
}
return true;
} catch (\Exception $ex) {
//display messgae
echo $ex->getMessage();
//or display error in flash message
//Yii::$app->session->setFlash('error',$ex->getMessage());
return false;
}
}
You can either return false in the catch part or return the error message rather than returning false and where ever you are calling the contact function check it the following way.
if(($r=$this->contact($email))!==true){
//this will display the error message
echo $r;
}

Login only first user error

Iam using the php 5.5 and pdo to create login code. the code is working fine but the only first user is loged in I don't know why? for example I have 5 user in my database table. when I login the first one then it goes to logedin but when I try to login the 2nd or 3rd one then it will show an error message which I set on incorrect data login. Below is my login code...
<?php
session_start();
include 'conn.php';
try
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$remember=$_POST['remember'];
$smt=$conn->prepare("SELECT * FROM signup");
$smt->execute();
$result=$smt->fetch(PDO::FETCH_OBJ);
$prev=$result->Password;
$usr=$result->Username;
if(password_verify($pass,$prev)& $user===$usr)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
$_SESSION['login']="Incorrect username or password";
}
if($remember)
{
setcookie('remember-me',$user,time()+3600000);
setcookie('remember-pass',$pass,time()+3600000);
header('location:index.php');
}
else
{
setcookie('remember-me',$user,false);
setcookie('remember-pass',$pass,false);
}
}
catch(PDOException $e)
{
throw new PDOException($e);
}
?>
Thanks in advance...
You are missing a WHERE CLAUSE :
SELECT * FROM signup WHERE Username = :user
adjust your code to the following:
$smt=$conn->prepare("SELECT * FROM signup WHERE Username =:user");
$smt->execute(array(':user'=>$user));
Please update your code with below code
<?php
session_start();
include 'conn.php';
try
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$remember=$_POST['remember'];
$smt=$conn->prepare("SELECT * FROM signup WHERE username = '".$user."' AND password = '".$pass."' ");
$smt->execute();
$result=$smt->fetch(PDO::FETCH_OBJ);
$prev=$result->Password;
$usr=$result->Username;
if(password_verify($pass,$prev)& $user===$usr)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
$_SESSION['login']="Incorrect username or password";
}
if($remember)
{
setcookie('remember-me',$user,time()+3600000);
setcookie('remember-pass',$pass,time()+3600000);
header('location:index.php');
}
else
{
setcookie('remember-me',$user,false);
setcookie('remember-pass',$pass,false);
}
}
catch(PDOException $e)
{
throw new PDOException($e);
}
?>

Codeigniter Displaying Information In A View?

I'm extracting two different sets of data from a function in my model (syntax below). I'm trying to display the data my view. I put the variable in var_dump and var_dump is displaying the requested information but I'm having a hard time accessing that information. I'm getting two different sets of error messages as well. They are below. How would I display the information in my view? Thanks everyone.
Site Controller
public function getAllInformation($year,$make,$model)
{
if(is_null($year)) return false;
if(is_null($make)) return false;
if(is_null($model)) return false;
$this->load->model('model_data');
$data['allvehicledata'] = $this->model_data->getJoinInformation($year,$make,$model);
$this->load->view('view_show_all_averages',$data);
}
Model_data
function getJoinInformation($year,$make,$model)
{
$data['getPrice'] = $this->getPrice($year,$make,$model);
$data['getOtherPrice'] = $this->getOtherPrice($year,$make,$model);
return $data;
}
function getPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
function getOtherPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
View
<?php
var_dump($allvehicledata).'<br>';
//print_r($allvehicledata);
if(isset($allvehicledata) && !is_null($allvehicledata))
{
echo "Cities of " . $allvehicledata->cardescription_id . "<br />";
$id = $allvehicledata['getPrice']->id;
$model = $allvehicledata[0]->model;
$make = $allvehicledata->make;
echo "$id".'<br>';
echo "$make".'<br>';
echo "$model".'<br>';
echo $allvehicledata->year;
}
?>
Error Messages
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_show_all_averages.php
Line Number: 7
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: views/view_show_all_averages.php
Line Number: 9
In your controller you are assigning the result of function getJoinInformation to the variable allvehicledata. This variable is then assigned to the view.
The function getJoinInformation is returning an array with the following
$data = array(
'getPrice' => $this->getPrice($year,$make,$model),
'getOtherPrice' => $this->getOtherPrice($year,$make,$model)
);
So in your view you can access the attributes getPrice and getOtherPrice in the object $allvehicledata like
$allvehicledata->getPrice;
$allvehicledata->getOtherPrice;
In line 7 you try to access the attribute cardescription_id, which is not an attribute of the object $allvehicledata.
I think this is an attribute which is get from the db query, so you should try to access it allvehicledata->getPrice->cardescription_id or allvehicledata->getOtherPrice->cardescription_id.
In line 9 you try to access some data stored in an array $model = $allvehicledata[0]->model;, but $allvehicledata is not an array.

Changing Member Password in MySQL through PHP

I've tried and tried creating a form to change your password, but I can't seem to get it right, please help! It is now telling me that "Query failed" each time I try to change the password, there are other variables such as username, first name that are involved however the user is only allowed to change their password so I had only included UPDATE members SET 'passwd' -- These are the variables created when someone initially registers, members(firstname, username, login, passwd, ip) VALUES('$fname','$uname','$login','".md5($_POST['password'])."','$ip')";
<?php
require_once('config.php');
require_once('auth.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$password = clean($_POST['password']);
$retpassword = clean($_POST['retpassword']);
//Input Validations
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($retpassword == '') {
$errmsg_arr[] = 'Please retype your password';
$errflag = true;
}
if( strcmp($password, $retpassword) != 0 ) {
$errmsg_arr[] = 'New passwords do not match!';
$errflag = true;
}
//If there are input validations, redirect back to the settings page
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: settings.php");
exit();
}
//Create UPDATE query
$qry = "UPDATE members SET 'passwd' = '".md5($_POST['password'])."' WHERE login = '{$_SESSION['username']}'";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: changed.php");
exit();
}else {
die("Query failed");
}
?>
This probably has to do more with the form you use to send the data.
Check the form method="POST" and check the names on your input fields.
Your form should look like this to be working with your PHP code
<form method="POST">
<input type="password" name="password">
<input type="password" name="retpassword">
</form>