Default Field Value to MySQL Database - php

I'm using a HTML form that captures user input for several fields, some of which can be left blank by the user, one particular field is called 'pasref'. What I would like to be able to do, if at all possible, is if this field is left blank by the user, for the default value to become the text 'Not Allocated' and for this to be saved as part of the record to a mySQL database.
I just admit I'm fairly new to this type of programming and I'm not sure whether this can be done within the mySQL database or whether it needs to be done as part of the php script that saves each record. I just wondered whether it would be at all possible please that someone could show me what I need to do?
I've included my PHP script below if it helps.
<?php
require("phpfile.php");
// Gets data from URL parameters
$userid = $_GET['userid'];
$locationid = $_GET['locationid'];
$pasref = $_GET['pasref'];
$additionalcomments = $_GET['additionalcomments'];
// Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = sprintf("INSERT INTO finds " .
" (userid, locationid, pasref, additionalcomments ) " .
" VALUES ('%s', '%s', '%s', '%s');",
mysql_real_escape_string($userid),
mysql_real_escape_string($locationid),
mysql_real_escape_string($pasref),
mysql_real_escape_string($additionalcomments));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>

You can set the default value on the column of mysql. You need to execute a query something like this:
ALTER TABLE finds MODIFY pasref varchar(100) default 'Not Allocated';
Change varchar(100) to whatever length it should be for your field.
Alternatively you could just set it in php:
if( empty($_GET['pasref']) ) {
$pasref = 'Not Allocated';
}
else {
$pasref = $_GET['pasref'];
}
Or finally you could put it as a default value in your form. Though the user would need to clear it if they want something else:
<input type="text" name="pasref" value="Not Allocated" />
Finally just to note in your PHP you need to escape your inputs to the database with mysql_real_escape_string or use PDO with placeholders. As is you have a SQL injection vulnerability.
It's also better to use POST. Change the form method to POST in your HTML and reference $_POST instead of $_GET

This can be solved by changing the column properties in the mysql database and setting the pasref column to not null and setting a default value.
Easily done if you can access the db using phpmyadmin

ALTER TABLE finds ALTER pasref SET DEFAULT = 'Not Allocated'
So when a new row is inserted with no value for column_name, Not Allocated with be used. It can also be done pretty easily with an interface like phpMyAdmin or MySQL Workbench if you have access to those tools.
Now all you have to do is check if pasref is empty in your PHP code and make sure you don't insert anything (an empty string "" is something) when it is the case.

you can just change the line
$pasref = $_GET['pasref'];
to
$pasref = $_GET['pasref'] == '' ? 'Not Allocated' : $_GET['pasref'];

Use this:
$query = " UPDATE $tabla SET fecha_ultimo_cambio=DEFAULT WHERE id in ($id) ";

Related

MYSQL PHP cannot insert or update with the same value

I have a table with two value.
ID, Building(is the name of Building)
i write a code with jquery to insert or Update the name of Building (i take the ID value from list1 and the new name from text_build)
function saveBuilding()
{
alert(document.getElementById("list1").value)
alert(document.getElementById("text_build").value)
$.get("saveBuilding.php",{ID:document.getElementById("list1").value, val:document.getElementById("text_build").value},
function(ret) { alert(ret);});
}
where my saveBuilding is:
<?php
$idbuilding=$_GET['ID'];
$name=$_GET['val'];
require_once '../../../dbconnection.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!db_server) die("Unable to connection_aborted to MySQL: " . mysql_error());
mysql_select_db($db_database) or die ("Unable to connection_aborted to MySQL: " . mysql_error());
$query = "UPDATE Building SET Name = '$name' WHERE ID_Building = '$idbuilding';";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
}
mysql_close();
?>
Now, if i update the value with a new value, it works, if i update the value with a value already used previously, it said that the query is successfully but it dont change nothing.
I try to insert new value by changing the query. and the result is the same.
i also try to add this value directly from mysql and it works!
so which is the problem in my code?
Thanks
MySQL is working as designed (and other rdbms). If you try to change a value to its current value, no error is thrown but nothing happens.
You just need to run
SELECT Name FROM your_table WHERE idbuilding=$id
then compare Name to what is already stored. If it's different, run your UPDATE; if not don't do anything because no action is required.
I solved the problem..
first i verified that the php code works.
and then i verified that the problem was the js.
i dont know why but changing the jquery function $.get in $.post now it work!!

Inserting data into two separate tables using PHP

I am trying to insert data into two different tables in the same database, if I try to insert it into one database, it works, however, once I insert the second query into my code ($desc_query) it won't update any table.
Here is my code:
$name= strip_tags($_POST['name']);
$l_name= strip_tags($_POST['last_name']);
$c_id = strip_tags($_POST['company_id']);
$a_d = strip_tags($_POST['add_description']);
$d_t = strip_tags($_POST['desc_text']);
$connect = mysql_connect('localhost','id','pass') or die ("couldn't connect!");
mysql_select_db('database_db') or die('could not connect to database!');
//inserting names
$job_query=mysql_query("INSERT INTO names VALUES ('', '$name', '$l_name')");
//inserting a new description if needed. (this is the part that ruins everything)
if($a_d == 'true'){
$desc_query=mysql_query("INSERT INTO descriptions VALUES ('','$c_id','$d_t')");
}
You might be having an issue where some characters (like ' and ") are breaking the SQL query (not to mention opening your application up for SQL injection attacks).
I would recommend sanitizing all user provided data like so:
$name = mysql_real_escape_string(strip_tags($_POST['name']), $connect);
$l_name = mysql_real_escape_string(strip_tags($_POST['last_name']), $connect);
...
$d_t = mysql_real_escape_string(strip_tags($_POST['desc_text']), $connect);
Always operate under the assumption that the user is going to enter something outlandish or malicious that may (or may not) break your SQL.
Have you tried to echo out the queries and then to run them directly on the database?
Without any more information about the database we can't really tell if the queries themselves are valid.

Update rows in mysql via id

Ok i have this code.
<? //process.php, this will be use in updating, adding, deleting items and content
$a = $_POST['hid'];
$b = $_POST['doctitle'];
$c = $_POST['doccontent'];
if (isset($_POST['hid']) && ($_POST['doctitle']) && ($_POST['doccontent']))
{
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
mysql_query("UPDATE doc SET title='$b', content='$c' WHERE id='$a'");
echo "<h2>Successfully updated.</h2>";
mysql_close($con);
}
else
{
echo "not been set, failed to process. please try again.";
}
?>
I want to update the specified row on the table doc, it should update the title in this $b and the content in this $C via id $a. but nothing happen, is there wrong in my code?, nxt is I want to know if the record has been update. thanks in advance.
If id is an integer column you shouldn't use ' around it's value:
WHERE id=$a
You can check number of affected rows using mysql_affected_rows() function:
$rowsAffected = mysql_affected_rows($con);
You should also check the query string and try to execute it on MySQL manually (on PhpMyAdmin, or something similar), to check if it works fine then.
Your code has no anti-SqlInjection parts. You should use PDO or any kind of escape function to make it more secure.
Are you sure that the if statement is firing (ie is $_POST['hid'] and the other post vars set)? Also, why do you run isset() on 'hid' and not the other 2 vars?
Oh, and as stated above, you should always sanitize your vars to protect against MySQL injection. You can always use mysql_real_escape_string

INSERT IGNORE In mySQL

I wonder whether someone can help me please.
I'm trying to put together a PHP script that takes data from an xml file and places the data in a mySQL data. I've been working on this for a few days and I'm still can't seem to get this right.
This is the code that I've managed to put together:
<?
$objDOM = new DOMDocument();
$objDOM->load("xmlfile.xml");
$Details = $objDOM->getElementsByTagName("Details");
foreach( $Details as $value )
{
$listentry = $value->getElementsByTagName("listentry");
$listentrys = $listentry->item(0)->nodeValue;
$sitetype = $value->getElementsByTagName("sitetype");
$sitetypes = $sitetype->item(0)->nodeValue;
$sitedescription = $value->getElementsByTagName("sitedescription");
$sitedescriptions = $sitedescription->item(0)->nodeValue;
$siteosgb36lat = $value->getElementsByTagName("siteosgb36lat");
$siteosgb36lats = $siteosgb36lat->item(0)->nodeValue;
$siteosgb36lon = $value->getElementsByTagName("siteosgb36lon");
$siteosgb36lons = $siteosgb36lon->item(0)->nodeValue;
//echo "$listentrys :: $sitetypes :: $sitedescriptions :: $siteosgb36lats :: $siteosgb36lons <br>";
}
require("phpfile.php");
//Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
mysql_query("INSERT IGNORE INTO scheduledsites (listentry, sitetype, sitedescription, siteosgb36lat, siteosgb36lon) VALUES('$listentrys','$sitetypes','$sitedescriptions','$siteosgb36lats','$siteosgb36lons') ")
or die(mysql_error());
echo "Data Inserted!";
?>
I can pull the data from the xml file, but it's the part of the script that sends the data to my database table that I'm having trouble with.
The script runs but only the last record is saved to the database.
I can parse the fields from the xml file without any problems and the check I'm trying to put in place is, if there is a 'listentry' number in the new data that is matched to one already in the table then I don't want that record to be added to the table, i.e. ignore it.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
You are only calling mysql_query once. So it will only insert one row.
The sql needs to be inside the loop.

PHP will not delete from MySQL

For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!

Categories