MySQL updates some records but not all (using PHP) - php

I am facing a strange issue.... I have created a PHP program using which I can update and delete records stored in MySQL table. The program has PHP-Session functionality for login-logout purpose. Now the issue is, when I am trying to edit records stored in database, few are updating fine but some are not updating at all. Rather it redirects me to index.php page. Initially I thought it was the session which is causing the issue, but when I removed the session code and tried to update the content, same thing happened and it redirects. The data is simple text with the some html formatting. Any idea... what could be the reason behind this...???
include "connection.php";
if($_POST['sub']=="Update"){
$upd=mysql_query("UPDATE table_3 SET title='".htmlentities($_POST['ttl'],ENT_QUOTES,'UTF-8')."', con='".htmlentities($_POST['con'],ENT_QUOTES,'UTF-8')."' WHERE mid='".$_POST['mid']."'");
if(mysql_affected_rows()!=-1){ echo "<script>alert ('!! Data Updated Successfully !!');</script>"; }
else{ echo "<script>alert ('!! Error Updating Data !!');</script>"; }
}
connection.php has this code -
mysql_connect("localhost","user_name","password") or die ("Unable to connect server bcoz ".mysql_error());
mysql_select_db("db_name") or die ("Unable to select database bcoz ".mysql_error());
Updating the same data directly on MySQL table works fine....
Here is the complete code [I trimmed out most of the styling tags, but the core code is same ] -
<?php
session_start();
if(!isset($_SESSION['user'])){ header("location:."); }
?>
<html>
<head>
<title>Edit - Update</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
</head>
<body>
<div>Logged In As: <b><?php echo $_SESSION['user']; ?></b><span class="logout"><b>Log Out</b></span>
</div>
<?php
include "connection.php";
if($_POST['sub']=="Update"){
$upd=mysql_query("UPDATE table_3 SET title='".htmlentities($_POST['ttl'],ENT_QUOTES,'UTF-8')."', con='".htmlentities($_POST['con'],ENT_QUOTES,'UTF-8')."' WHERE mid='".$_POST['mid']."'");
if(mysql_affected_rows()!=-1){ echo "<script>alert ('!! Module Updated Successfully !!');</script>"; }
else{ echo "<script>alert ('!! Error Updating Module Info !!');</script>"; }
}
//URL of the page is - http://url/edit.php?mid=49
$res=mysql_query("SELECT * FROM table_3 WHERE mid='".$_GET['mid']."'");
$row=mysql_fetch_row($res);
?>
<form name="eform" method="post" action="">
<table style="margin-left:10px;">
<tr><td><font color="#025A8D"><b>Title : </b></font></td><td><input type="text" name="ttl" value="<?php echo ucfirst($row[2]); ?>" size="75" /></td></tr>
<tr><td><font color="#025A8D"><b>Content : </b></font></td><td><textarea name="con" cols="72" rows="20"><?php echo html_entity_decode($row[3],ENT_QUOTES,'UTF-8'); ?></textarea></td></tr>
<tr><td> <input type="hidden" name="mid" value="<?php echo $_GET['mid']; ?>" /></td></tr>
<tr align="center"><td></td><td><input type="submit" name="sub" value="Update" /></td></tr>
</table>
</form>
</body>
</html>

Related

PHP Myqsli Form automatically returning to previous page in Chrome but not in Edge?

I have a form that submits fields to a database using mysqli that was working perfectly; however, I pulled up the form page in Chrome and tried to submit a new row to the db, only for the page to go back to the previous page when I tried to click on the form's text-areas. I tried clearing all of my browser history (cache, cookies, etc.) and asked a friend to try it on their Chrome browser, with the same result.
The kicker? It works in Edge. Makes no sense.
I've gone through the code and can't find any missing <'s or quotes, etc. Everything was working fine and I can't imagine why it would suddenly start doing this in Chrome.
(Note: I know this code is clunky and vulnerable to SQL injection, but I don't have any users/sensitive data to protect, for the moment. Also, I made no changes to head.php or any code (that I can recall), just confused as to why it would suddenly start redirecting me back to notebook.php as soon as I click on a text area in Chrome but not in Edge.)
Notebook_add.php
$con = #mysqli_connect('localhost', 'root', 'pass', 'db');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
?>
<body>
<div class="wrapper">
<h1>Post Comments</h1>
<?php
include ('navbar.php');
?>
<br>
<form name="noteworthy" METHOD=POST action=<?php echo $_SERVER['PHP_SELF']; ?>>
<br>
Title: <input type="text" name="title" id="$title" size="50"> <br>
Link: <input type="text" name="link" id="$link" size="50"><br>
Description: <TEXTAREA NAME="description" id="$description" ROWS="5" COLS="30"></TEXTAREA><br>
<Input type="submit" name="enter" id="$enter" value="enter">
</form>
<?
echo $submitted = date("Y-m-d");
?>
<?
$title = $_REQUEST['title'];
$link = $_REQUEST['link'];
$description = $_REQUEST['description'];
$enter = $_REQUEST['enter'];
if(isset($_REQUEST['enter'])){
$submitted = date("Y-m-d");
$sql = "INSERT INTO notes (title, link, description, submitted) VALUES ('$title','$link','$description','$submitted')";
}
if(mysqli_query($con, $sql)){
echo "Records inserted successfully.";
print "<meta http-equiv='refresh' content='0; url=http:notebook.php' />";
}
// Close connection
mysqli_close($con);
?>
<div class="push"> </div>
</div>
<?php
include 'footer.php';
?>
</body>
So what happened was that I had added a new menu item in my navbar.php and forgot to close the link tag (e.g., " New menu item "). This made the entire php form into a link, so whenever I anywhere on it under my navbar I was returned to the previous page.
It is interesting that this didn't happen in Edge; perhaps there is some feature in Edge that automatically closes rogue tags.
Anyway, thanks for responding. #Smith, thanks for the tip, I'm using the php head featured/location function instead of meta-refresh now.

change from mySQL to SQL and now cant get record creation

I am running WAMP 2.5 on Win7 and created a webpage to insert records into a mySQL database. This worked perfectly.
Then I needed to use SQL Server 2014 (remote server on LAN) instead of mySQL (local in WAMP), and while everything seems ok, i am not getting the records created in the table, yet no error either.
Account used to log in with is db owner.
Any help would be great.
Thanks
Len
Code is as follow (I call sqlconnect.php for db connection) and get confirmation that connection was successful.
File is called insert-data.php so it calls itself if form is empty and Submit is selected.
<?php
if(!empty($_POST['mcpbarcode'])) {
header("Location insert-data.php");
include('sqlconnect.php');
$mcpbarcode = $_POST['mcpbarcode'];
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES ('$mcpbarcode')";
sqlsrv_query($conn,$sqlinsert);
if (!$sqlinsert) {
die('error inserting new record');
}
$newrecord = "New record added";
}
?>
<html>
<head>
<title> Insert Barcode into Database</title>
</head>
<h3><font color = red>This window must be open and active</font></h3>
<img src="header.jpg" alt="anyname" style="width:800px;height:165px;">
<body>
<h1> Insert barcode into Database</h1>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<label>Barcode:<input type="text" name="mcpbarcode" autofocus /></label>
<br /><br />
<input type="submit" value="Add new record" />
</form>
<?php
$newrecord="";
echo $newrecord
?>
</body>
</html>
See if it's working like that:
If mcpbarcode column is a string type (varchar, char etc):
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES ('".$mcpbarcode."')"
OR if mcpbarcode column is int, float, etc:
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES (".$mcpbarcode.")"
but you should have an error on mysql also ...

PHP - Recalling information stored in database using sessions

I've got problem when using sessions to recall data stored in mySQL database. This is my code:
The login page is simple, the input your username and password kind (i know the password is still plaintext, i plan to change it later).
<?php
$host="localhost";
$user="root";
$pass="";
$db_name="proyek";
$tbl_name="murid";
mysql_connect("$host", "$user", "$pass")or die("Cannot connect to SQL.");
mysql_select_db('$db_name');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div id="header">
LOGO
<h1 align="center">TITLE</h1>
</div>
<br/>
<div id="login">
<form id="loginform" name="loginform" method="post" action="checklogin.php">
<table border="0" align="center">
<tr>
<td>NIS</td>
<td></td>
<td><input type="text" name="nislogin" id="nislogin"/></td>
</tr>
<tr>
<td>Password</td>
<td></td>
<td><input type="password" name="pwdlogin" id="pwdlogin"/></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="loginbutton" id="loginbutton" value="Login"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
and this is the code for login check page:
<?php
session_start();
$host="localhost";
$user="root";
$pass="";
$db_name="proyek";
$tbl_name="murid";
mysql_connect("$host", "$user", "$pass")or die("Cannot connect to SQL.");
mysql_select_db('$db_name');
$nis=($_POST['nislogin']);
$pwd=($_POST['pwdlogin']);
$sql="SELECT * FROM murid WHERE nis='$nis' and password='$pwd'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
$_SESSION['nislogin']=$nis;
$nama=$result['nama'];
$_SESSION['nama']=$nama;
header("location:index.php");
return true;
exit;
}
else
{
echo("Wrong NIS or password.");
return false;
}
?>
i have entered some dummy data in database for testing purposes; id, password, name. how can i recall something from database while user only login with username/id?
i'd like to display something like 'hello, name' in the next page. Help is appreciated.
edit: I've edited my code based on feedbacks and it produces blank; like 'Hello,' with no name.
First of all, since you are running a query on your login check page, use that value for your session rather than the post data. Also, whenever you are redirecting, always exit your script.
EDIT:
Since you are in the development stage, you need to display an error if your query fails so you know why. I also realized you need to return an associative array to access the row. Try this.
$sql="SELECT * FROM murid WHERE nis='$nis' and password='$pwd'";
$result=mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$count=mysql_num_rows($result);
if($count==1)
{
$data=mysql_fetch_assoc($result); // since you are only accessing one row,
// otherwise you would put this in a loop to build your array.
session_start();
$_SESSION['nislogin']=$data['nis'];
header("location:index.php");
return true;
exit;
}
I also see this session on your login page, but I don't see that you ever created it and I don't see the purpose.
if(isset($_SESSION['nama']))
{
unset($_SESSION['nama']);
}
Basically all you need from here, is to start the session on index.php and output it.
index.php
session_start();
if(isset($_SESSION['nislogin']))
{
$name = $_SESSION['nislogin'];
} else {
$name = "stranger";
}
<body>
Welcome, <?=$name?>
</body>

Passing session variables from html form to multiple php page urls?

I'm trying to pass variables from the form to multiple pages in php
The form "rentcheck.php"
<?php require ("Connections/Project.php") ;?>
<?php session_start();?>
<title>Rent Check</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="rent.php">
<table width="385" height="70" border="1">
<tr>
<td><label for="select3">Select Customer</label>
<select name="Customer_ID" id="Customer_ID">
<?php
//Select from SQL Database Table (t_customer)
$sql=mysql_query("SELECT * from t_customer");
while ($Customer = mysql_fetch_array($sql)){
echo "<option value='".$Customer['Customer_ID']."'>".$Customer['Customer_Name']."</option>";
}
?>
</select></td>
</tr>
</table>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
After input and Pass it to page "rent.php"
<?php
require("Connections/Project.php");
//$_SESSION['yourvariable'] = 'foo';
//$newDate = date("d-m-Y", strtotime($row_Recordset1['Customer_CC_Exp_Date']));
session_start();
$datetoday=date("Y-m-d H:i:s");
$endOfCycle=date('Y-m-d', strtotime("+30 days"));
if(isset($_GET['page'])){
$pages=array("products","cart");
if(in_array($_GET['page'], $pages)){
$_page=$_GET['page'];
}else{
$_page="products";
}
}else{
$_page="products";
}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rent</title>
</head>
<body>
<p> <?php require($_page. ".php");?>
<?php echo $_POST['Customer_ID'];?></p>
</body>
</html>
This page (rent.php) shows the value from the form.
And the third page "products.php"
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<?php
if(isset($_GET['action']) && $_GET['action']=="add"){
$custget=$_SESSION['Customer_ID'];
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id][$custget])){
$_SESSION['cart'][$id]['quantity']++;
$getcust=$_SESSION['Customer_ID'];
}else{
$sql_s="SELECT * FROM t_dvd_copy
WHERE dvd_copy_id={$id}";
$query_s=mysql_query($sql_s);
if(mysql_num_rows($query_s)!=0){
$row_s=mysql_fetch_array($query_s);
$_SESSION['cart'][$row_s['dvd_copy_id']]=array(
"quantity" =>1,
"price" => $row_s['price']
);
}else{
$message="NO";
}
}
}
?>
<?php if(isset($message)) {
echo"$message"; }
//echo print_r($_SESSION['cart']); ?>
<table width="489" height="52" border="1">
<tr>
<td width="123">DVD Copy ID</td>
<td width="120">Name</td>
<td width="91">Price</td>
<td width="127">Action</td>
</tr>
<?php
$sql="SELECT *, dvd_title FROM t_dvd_copy INNER JOIN t_dvd ORDER BY dvd_title ASC";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query)) {
?>
<tr>
<td><?php echo $row['dvd_copy_id']?></td>
<td><?php echo $row['dvd_title']?></td>
<td><?php echo $row['price']?></td>
<td>Add To Cart</td>
<?php
}
?>
</table>
<body>
</body>
</html>
This page (products.php) shows:
Notice: Undefined index: Customer_ID in C:\xampp\htdocs\project3\rent.php on line 39" whenever I clicked the "Add to Cart" or manually type "rent.php?=cart".
I'm trying to do is to show(Customer_ID)/pass the variables on multiple pages("products.php","cart.php").
Any suggestions or ideas?
I think your problem is that you have not started the session on the other pages.
on every php page that you want to have a session you need to put session_start(); at the top.
if you don't the session will end and empty all the data from it.
if you want to make sure what is in your session you can print it out like so:
echo "<pre>";
echo print_r($_SESSION);
echo "</pre>";
Couple of things:
You mentioned that when you clicked "Add to Cart" it didn't work. I assume you mean the button labelled "Submit" on the rentcheck.php page. Can you confirm this is right please?
You would get an error when manually navigating to rent.php?=cart as you are looking for a Customer_ID key in the $_POST array but at this point you are not posting to the server, you are performing a $_GET request.
You have referenced $_SESSION['Customer_ID'] but I cannot see in your code where you have set this (products.php 7th line of code).
I would suggest thinking through how a user might navigate through your website:
where are they likely to start?
what variables will be available to you at this point?
what will you do if the required variables do not exist (e.g. $_SESSION)?
what is the earliest point you can collect the required information (your form)?
once the form has been completed correctly, how can I make sure that the required information is retained throughout the users session?
have I continued to test on each page that my required variables are available to me?
Start with that and see where it leads you.
Looking at the code I can see that you are including products.php inside rent.php
So a couple of thoughts here:
products.php should not have HTML <head> because it will be rendered
inside the <body>
If you have a variable available in rent.php it will be available
under the same name in products.php.
So if you have in rent.php:
$customer_id = $_POST['Customer_ID'];
require('products.php');
In products.php you can use $customer_id directly.

session_start problems when run process in parallel

I need that both iframes forms work independent (async) but when i submit both forms at the same time the second iframe report "Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\iframe2.php on line 2" (when the iframe1 query is a long process) or the second iframe return data AFTER the first process is complete (when the iframe1 query is a short process).
Now, i need keep the session for validate user login.
i need your help, my friends! thanks
index.php
<html>
<head>
<title></title>
</head>
<body>
<iframe src="iframe1.php" width="300" height="400"></iframe>
<iframe src="iframe2.php" width="300" height="400"></iframe>
</body>
</html>
iframe1.php (return query results)
<?php
session_start();
if($_SESSION['user'])
$data="Valid user";
else
header("location: login.php");
set_time_limit(120);
require_once("config.php"); //db conections
if($_POST)
{
//query (long process)
$data.= ""; // concatenated string with query results
}
?>
<html>
<head>
<title></title>
</head>
<body>
<?php echo session_id();?>
<form method="post">
ini:<input type="text" name="var1" value="" /><br />
fin:<input type="text" name="var2" value="" /><br />
<input type="submit" value="Send" />
</form>
Result:<br />
<?php
if(isset($data))
echo session_id()."<hr>".$data;
?>
</body>
</html>
iframe2.php (only return 123456)
<?php
session_start();
if($_SESSION['user'])
$data="Valid user";
else
header("location: login.php");
if($_POST)
{
$data = "123456";
}
?>
<html>
<head>
<title></title>
</head>
<body>
<?php echo session_id();?>
<form method="post">
<input type="text" name="inpt" />
<input type="submit" value="frame2" />
</form>
Result:<br />
<?php
if(isset($data))
echo session_id()."<hr>".$data;
?>
</body>
</html>
Default PHP session have blocking file-access. That means as long as in your first script the session is still active, the second script's access to the session is blocked. PHP will wait until the session is accessible again.
The solution often is to keep the time-span short for the active period. Normally the sessions does not need to be active all the time.
You activate a session with session_start().
You deactivate a session with session_commit().
Locate the part of your script where you actually need an active session. Open it as late as possible (start) and close (commit) it as soon as possible.

Categories