PHP - reload new record upon page refresh - php

I have a little problem with my PHP code and database. Every time i refresh the page, a new empty row is being added to the database also when i open the page, what is the problem?
<?php
if (isset($_POST)) {
$con = mysql_connect("localhost","dwarfmaster","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_dwarfmaster", $con);
$name = $_POST['name'];
$release_year = $_POST['release_year'];
$publisher = $_POST['publisher'];
$genre = $_POST['genre'];
$sql = "INSERT INTO gamelist (name, release_year, publisher, genre)
VALUES
('$_POST[name]','$_POST[release_year]',
'$_POST[publisher]','$_POST[genre]')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
}
?>

to check if the request method is post, use:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
if(isset($_POST)) will always return true

or simply change
if (isset($_POST))
to
if (isset($_POST['name']))

you can add the following code-:
if( !empty(array_filter($_POST)) ) { . . Code to insert data into data base
from form . . }

if (isset($_POST))
will always return true !
try
if (isset($_POST['name'])&&isset($_POST['release_year'])
&&isset($_POST['publisher'])&&isset($_POST['genre']))
instead to check each time for each and every variable !

Related

how to UPDATE using mysql_insert_id() into different table?

I am using mysql_insert_id() on the first page (test2.php) to insert the same id on other tables that is submitted from different forms. The id is inserted perfectly however, when i want to insert the data from other forms (e.g: test.php), the data cannot be updated, I have to inform before this i was using insert and it is not systematic because it will insert a new data with new id. As reference, below are my php codings for page test2.php and test.php:
test2.php:
<?php
session_start();
include("auth.php");
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('tempahperalatan');
if(isset($_POST['submit'])){
$noID = $_POST['noID'];
$pemohon = $_POST['pemohon'];
$trkhMula = $_POST['trkhMula'];
$trkhAkhir = $_POST['trkhAkhir'];
$n_program = $_POST['n_program'];
$lokasi = $_POST['lokasi'];
$n_anjuran = $_POST['n_anjuran'];
$catatan = $_POST['catatan'];
mysql_query("INSERT INTO daftartempah (noID, pemohon, trkhMula, trkhAkhir, n_program, lokasi, n_anjuran, catatan) values ('$noID','$pemohon','$trkhMula','$trkhAkhir','$n_program','$lokasi','$n_anjuran','$catatan')");
mysql_query("INSERT INTO pasystems (noID) values ('$noID')");
mysql_query("INSERT INTO ict_1 (noID) values ('$noID')");
mysql_query("INSERT INTO pejabat (noID) values ('$noID')");
printf("Last inserted record has id %d\n", mysql_insert_id());
}
?>
For page test.php, there is an echo of variables is because I was testing whether it reads the variables, and surprisingly it reads because it appear at the top of the page of the data that I entered however, the noID does not appear and that means it does not fetch the same id from the previous page (test2.php) and I think that is the problem why my data was not updated. Can anyone help me about this problem because I'm a student studying web programming and some guidance would be so helpful, thank you in advance.
test.php:
<?php
session_start();
include("auth.php");
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('tempahperalatan');
if(isset($_POST['submit'])){
$noID = $_POST['noID'];
$microphones = $_POST['microphones'];
$amplifiers = $_POST['amplifiers'];
$loudspeakers = $_POST['loudspeakers'];
$mixers = $_POST['mixers'];
$catatan = $_POST['catatan'];
?>
<p><?php echo $microphones;echo $amplifiers; echo $loudspeakers; echo $mixers; echo $catatan; echo $noID; ?></p>
<?php
mysql_query ("UPDATE pasystems SET microphones='$microphones', amplifiers='$amplifiers', loudspeakers='$loudspeakers', catatan='$catatan' WHERE noID = '$noID'");
}
Please ask if my question is not clear for you to help me, I will try to help you understand my problem/question.

headers not working PHP

Page 1 abc.html.. on submit it will jump to this PHP page .
This is page PHP1.php here i am trying to validate user input if name and id in in data he will be forwarded to fill out second part of registration if not it will just give error.
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = mysql_connect("localhost", "user", "password");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db("mydbName");
if(isset($_POST['team_name'],$_POST['id'])){
$team_name = mysql_real_escape_string($_POST['team_name']);
$id = mysql_real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result= mysql_query("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$team_result = mysql_fetch_row($result);
if ($team_result[0] == '0') { //if does not exist print failed.
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}} } ?>
RegisterPART2.php is where i am checking my session exist or not (the one i started in last file). if not i want to redirect back to form one and fill that first then come to registration part 2
`<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
header('Location: http://www.abc.com/page1.html'); //take back to stage 1 coz user did not fill first part.
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>
If you're using the new MySQL version (MySQLi), so the first page will become:
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = new mysqli("localhost", "user", "password", "mydbName");
if (!$con) {
die('Could not connect: ' . $con->error());
};
if (isset($_POST['team_name'],$_POST['id'])) {
$team_name = $con->real_escape_string($_POST['team_name']);
$id = $con->real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result = $con->prepare("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$result->execute();
$result->bind_result($one,$two,$three,$etc);
$result->fetch();
if (empty($one) and empty($two) and empty($three) and empty(etc)) { // may be and/or (pick one)
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}
}
}
?>
You may use the following alternative to header.
prinf('<script>window.location = "URL HERE"</script>');
It should do the same thing as header does.

inspect data (url variable) before inserting to mysql

My php script is posting bad urls that ajax send to it. When I try to filter the url and cancel the insert into mysql, it doesn't work. What I want to do is verify the $link variable if it a link. If not, don't post data to mysql. Can i know what I did wrong and how to fix it? Thank you :)
Here is my code
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$link = $_POST['new'];
$name = $_POST['name'];
$size = $_POST['size'];
$cat = $_POST['cat'];
// PHP 5.3.5-1ubuntu7.2
$link = mysql_real_escape_string($link);
$name = mysql_real_escape_string($name);
$size = mysql_real_escape_string($size);
$cat = mysql_real_escape_string($cat);
if (filter_var($link, FILTER_VALIDATE_URL)) {} else {
echo "URL is NOT valid";
mysql_close($con);
exit();
}
$check = mysql_query("SELECT link FROM links WHERE link = '{$link}';");
if (mysql_num_rows($check) == 0) {
// insert
$sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added. Redirecting!";
mysql_close($con);
}
try this one:
if(filter_var($link, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === false){
echo "URL is NOT valid";
mysql_close($con);
exit();
}
Your are right xxxhxtxtp://example.com will pass as valid url.
Try it with preg_match instead.
if (!preg_match("#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i", $link)) {
echo "URL is NOT valid";
mysql_close($con);
exit();
}
With this regex you need to have http(s) scheme. So you can search for another regex if that don't work for you.
Is this what you're trying to do? Perhaps you need a regex solution.
if (filter_var($link, FILTER_VALIDATE_URL)) {
$check = mysql_query("SELECT link FROM links WHERE link = '{$link}';");
if (mysql_num_rows($check) == 0) {
// insert
$sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added. Redirecting!";
mysql_close($con);
}
} else {
echo "URL is NOT valid";
mysql_close($con);
exit();
}

PHP update won't properly update database

The following code is part of my ajax notification system and for some reason, it is working only 50%. When I call the code, it runs and then echo's either success or remove but it doesn't seem to change the database values. Any reason? I have tried putting my column names in quotes but that echo's an error. Please help, thanks!
<?php
require_once('.conf.php');
$notid = mysql_real_escape_string($_GET['notification_id']);
$username = mysql_real_escape_string($_SESSION['uname']);
$action = mysql_real_escape_string($_GET['action']);
if ($action == 'add') {
$insert = mysql_query("UPDATE updates SET object_fav = '1' WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'success';
} elseif($action == 'sub') {
$remove = mysql_query("UPDATE updates SET object_fav = '0' WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'remove';
} else {
echo 'error';
}
?>
I know it is not the javascript, I have checked the network tab and it is sending the correct values.
If this is the start of the script, you have not called session_start(), and therefore $_SESSION['uname'] will contain an empty value. The query succeeds because it is syntactically correct, but doesn't match any rows and therefore performs no update.
session_start();
require_once('.conf.php');
$notid = mysql_real_escape_string($_GET['notification_id']);
$username = mysql_real_escape_string($_SESSION['uname']);
$action = mysql_real_escape_string($_GET['action']);
Echo $insert and $remove and find which values are missing.

Check To See A Match In MySql

I have a form which has a textbox with an attribute called ref. once this is submitted, it updates on of my fields in the database. I have this code working and fine but what i need now is for it to check if the data entered into the textbox exists in the database and if it does, then it should notify the user to choose another reference. here is my code for the php end:
$ref = mysql_real_escape_string($_REQUEST['ref']);
$id = $_GET['public'];
$con = mysql_connect("localhost", "*****", "******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('*****', $con);
$sql = "UPDATE public SET ref = '$ref' WHERE public_id = '$id'";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
any ideas guys?
thanks
You can get the number of rows affected:
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
//something WAS changed!
}
else {
//NOTHING was changed ... :-(
}
Also I would watch out for Bobby Tables
You might want to use mysqli or PDO's prepared queries for what you want to do.
Based on OP's comment below:
...
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
else {
//show some error message?
}
}
In this case First you run a select command to search for the record with particular reference number. If the result is eof , then run insert command. If not EOF then send a warning to the user saying reference number exist and choose another one.

Categories