My PHP PDO update counter in MYSQL does +3 instead of +1? - php

I want to count the amount of updates made on a record. The field name is pm_v. I got the following codes:
Update function:
function update_products_materials(){
$query = "UPDATE
" . $this->table_name . "
SET
pm_id = :pm_id1,
pm_code = :pm_code,
pm_name = :pm_name,
pm_department = :pm_department,
pm_temp = :pm_temp,
pm_color = :pm_color,
pm_v = pm_v +1
WHERE
pm_id = :pm_id2";
$stmt = $this->conn->prepare($query);
$this->pm_id=htmlspecialchars(strip_tags($this->pm_id));
$this->pm_code=htmlspecialchars(strip_tags($this->pm_code));
$this->pm_name=htmlspecialchars(strip_tags($this->pm_name));
$this->pm_department=htmlspecialchars(strip_tags($this->pm_department));
$this->pm_temp=htmlspecialchars(strip_tags($this->pm_temp));
$this->pm_color=htmlspecialchars(strip_tags($this->pm_color));
$stmt->bindParam(':pm_id1', $this->pm_id);
$stmt->bindParam(':pm_id2', $this->pm_id);
$stmt->bindParam(':pm_code', $this->pm_code);
$stmt->bindParam(':pm_name', $this->pm_name);
$stmt->bindParam(':pm_department', $this->pm_department);
$stmt->bindParam(':pm_temp', $this->pm_temp);
$stmt->bindParam(':pm_color', $this->pm_color);
$stmt->execute();
return $stmt;
}
This is the only place where I use pm_v.
The function is called in the following code:
$database = new Database();
$db = $database->getConnection();
// initialize objects
$products_materials = new Products_Materials($db);
$products_materials->id = $id;
$products_materials->view_products_materials();
$products_materials->update_products_materials();
if(isset($_POST["update"])){
$products_materials->pm_id=$id;
$products_materials->pm_code=$_POST['pm_code'];
$products_materials->pm_name=$_POST['pm_name'];
$products_materials->pm_department=$_POST['pm_department'];
$products_materials->pm_temp=isset($_POST['pm_temp']) ? $_POST['pm_temp'] : '';
$products_materials->pm_color=isset($_POST['pm_color']) ? $_POST['pm_color'] : '';
if($products_materials->update_products_materials() && (isset($_POST["update"]))){
header("Location: view_products_materials.php?id={$id}");
$_POST=array();
} else {
echo "<div class='alert alert-danger' role='alert'>Unable to save record.</div>";
}
}
Somehow, when I update a record it does +3 instead of +1. Can anyone explain why this is happening and how I can get it right?

Related

How to update status in database if status is empty without submitting a form in php?

How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.

Not able to insert the data from url to database in php

final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function

Error mysqli_insert_id

Using the PHP manual I created following code:
$query = "INSERT INTO inserir(nome) VALUES ('Stefanato');";
$listar = new consultar();
$listar->executa($query);
echo "New record has id: " . mysqli_insert_id($listar->$query);
I also used this answer for class connections: Error mysqli_select_db
But I keep getting this error:
Warning: mysqli_insert_id () expects parameter exactly 1, 2 given in
/home/controle/public_html/demo/teste.php on line 9
How do I fix that?
Here is the simple example for getting the id of last record created-
Code is taken from here
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Edit: Here is working code
<?php
define("SERVIDOR_BD", "localhost");
define("USUARIO_BD", "usuario");
define("SENHA_BD", "senha");
define("BANCO_DE_DADOS", "dados");
class conecta {
public $database_bancoDados = null;//1. New Added Field
public $bancoDados = null;//2. New Added Field
function conecta($servidor="", $bancoDeDados="", $usuario="", $senha=""){
if (($servidor == "") && ($usuario == "") && ($senha == "") && ($bancoDeDados == "")){
$this->bancoDados = mysqli_connect(SERVIDOR_BD, USUARIO_BD, SENHA_BD) or trigger_error(mysqli_error(),E_USER_ERROR);//3. Store in class variable
$this->database_bancoDados = BANCO_DE_DADOS;//4. Store in class variable
} else {
$this->bancoDados = mysqli_connect($servidor, $usuario, $senha) or trigger_error(mysqli_error(),E_USER_ERROR);//5. Store in class variable
$this->database_bancoDados = $bancoDeDados;//6. Store in class variable
}
}
}
class consultar {
var $bd;
var $res;
var $row;
var $nrw;
var $data;
function executa($sql=""){
if($sql==""){
$this->res = 0; // Pointer result of the executed query
$this->nrw = 0; // Line number the query returned, cruise control
$this->row = -1; // Array of the current query line
}
// Connects to the database
$this->bd = new conecta();//7. Store in class variable
$this->bd->conecta();//8. Store in class variable
mysqli_select_db($this->bd->bancoDados, BANCO_DE_DADOS);//9. Change Here For parameter sequence
$this->res = mysqli_query($this->bd->bancoDados, $sql); //10. Change here for parameter sequence
$this->nrw = #mysqli_num_rows($this->res);
$this->row = 0;
if($this->nrw > 0)
$this->dados();
}
function primeiro(){
$this->row = 0;
$this->dados();
}
function proximo(){
$this->row = ($this->row<($this->nrw - 1)) ?
++$this->row:($this->nrw - 1);
$this->dados();
}
function anterior(){
$this->row = ($this->row > 0) ? -- $this->row:0;
$this->dados();
}
function ultimo(){
$this->row = $this->nrw-1;
$this->dados();
}
function navega($linha){
if($linha>=0 AND $linha<$this->nrw){
$this->row = $linha;
$this->dados();
}
}
function dados(){
mysqli_data_seek($this->res, $this->row);
$this->data = mysqli_fetch_array($this->res);
}
}
$query = "INSERT INTO inserir(uname) VALUES ('Stefanato');";
$listar = new consultar();
$listar->executa($query);
echo "New record has id: " . mysqli_insert_id($listar->bd->bancoDados);//11. Change Here for parameter

Resource id #6 error, Not sure how to fix it

I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.

Functions not able to find variable?

I have the following variable $user_id being set by
//Check if user is logged in
session_start();
if (!isset ($_SESSION['user_id']))
{
header("location:login.php");
}
elseif(isset ($_SESSION['user_id']))
{
$user_id = $_SESSION['user_id'];
}
and then within the same function file I have the following:
function course_menu()
{
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = mysql_query($sqlSubscription);
while ($rows = mysql_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
}
The problem is I keep getting undefined variable user_id every time I try to run the function. I can echo $user_id on another page lets say index.php by using require_once function.php and then echo $user_id, but for some reason the function itself can't access it?
I think it might be because it's outside its scope - but if so I'm not entirely sure what to do about it.
My question is, how can I get the function to be able to use the variable $user_id?
EDIT
So I've started doing
$user_id = $_SESSION['user_id'];
global $conn;
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = $conn->query($sqlSubscription);
while ($rows = mysqli_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
which seems to work fine, but it's a bit tedious to add a new connection each time with a function or set the $user_id manually. Is there any way around this as I have several functions that require a connection to the db to pull data. Is there a better way to structure this type of stuff? I'm not very familiar with OOP but I can try it out if I can get some direction, here's another function that I use (and there are at least another 5-6 that require db connections)
function render_dashboard()
{
$user_id = $_SESSION['user_id'];
global $conn;
//Following brings up the number of subscription days left on the user dashboard
$sqlDate = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'" ;
$date = $conn->query($sqlDate);
while ($daterows = mysqli_fetch_assoc($date))
{
$course_registered = $daterows['course_title'];
$date_time = $daterows['end_date'];
$calculate_remaining = ((strtotime("$date_time")) - time())/86400;
$round_remaining = round("$calculate_remaining", 0, PHP_ROUND_HALF_UP);
// Here we assign the right term to the amount of time remaining I.E DAY/DAYS/EXPIRED
if($round_remaining > 1)
{
$remaining = $course_registered." ".$round_remaining." "."Days Remaining";
$subscriptionStatus = 2;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining == 1)
{
$remaining = $course_registered." ".$round_remaining." "."Day Remaining";
$subscriptionStatus = 1;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining <= 0)
{
$remaining = $course_registered." "."Expired"." ".$date_time;
$subscriptionStatus = 0;
echo '<p>',$remaining,'</p>';
}
}
//Check for most recent viewed video
$sqlVideo = "SELECT `last_video` FROM users WHERE `user_id` = '".$user_id."'" ;
$videoResult = $conn->query($sqlVideo);
if ($videoRows = mysqli_fetch_assoc($videoResult))
{
$last_video = $videoRows['last_video'];
$videoLink = "SELECT `chapter_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($chapteridResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$chapter_id = $chapteridResult['chapter_id'];
}
$videoLink = "SELECT `course_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($courseResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$course_id = $courseResult['course_id'];
}
}
}
The function course_menu() will not recognize your $user_id, Since it is outside its scope.
Make use of global keyword to solve this issue.
function course_menu()
{
global $user_id;
// your remaining code .........
The solution to getting around it without using global is to either DEFINE and pass it through ie - define ('var', '$var') then function x($var) or dependency injection as stated here How can I use "Dependency Injection" in simple php functions, and should I bother?

Categories