MYSQL PHP cannot insert or update with the same value - php

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!!

Related

Cannot Display Data from MySQL table

I've got a pretty standard call to a MySQL database and for some reason I can't get the code to work. Here's what I have:
$mysqli = mysqli_connect("localhost","username","password");
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
session_start();
$sql = "SELECT * FROM jobs ORDER BY id DESC";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
Now, first, I know that it is connecting properly because I'm not getting the die method plus I added an else conditional in there previously and it checked out. Then the page displays but I get the errors:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 11
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 12
I've double-checked my database and there is a table called jobs with a row of "id" (it's the primary row). The thing that confuses me is this is code that I literally copied and pasted from another site I built and for some reason the code doesn't work on this one (I obviously copy and pasted it and then just changed the table name and rows accordingly).
I saw the error and tried:
$num_rows = $mysqli_result->num_rows;
$row_array = $mysqli_result->fetch_array;
and that fixed the errors but resulted in no data being passed (because obviously $mysqli_result has no value). I don't know why the error is calling for that (is it a difference in version of MySQL or PHP from the other site)?
Can someone help me track down the problem? Thanks so much. Sorry if it's something super simple that I'm overlooking, I've been at it for a while.
You didn't selected the database
$mysqli = mysqli_connect("localhost","username","password","database");
The problem is you haven't selected the database.
use this code for select database.
$mysqli = mysqli_connect("localhost","username","password");
mysqli_select_db("db_name",$mysqli);
You have to select database in order to fire mysql queries otherwise it will give you error.
I believe that schtever is correct, I do not think you are selecting the database. It isn't in the code snip and if you search online you see other people with similar errors and it was because the database wasn't selected. Please let us know if you selected a database before anything else is checked. Thanks.
Try this:
session_start();
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
$mysqli->close();
}
$query ="SELECT * FROM jobs ORDER BY id DESC";
$values = $mysqli->query($query);
if($values->num_rows != 0)
{
while($row = $values->fetch_assoc())
{
//your results echo here
}
}
else
{
//if no results say so here
}
See this manual for mysqli_connect you can select the database right in this function.

Basic MySQL help? - submitting data

I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code
<IMG>
I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
$mysqli = mysqli_init();
//Log in to the DB
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)
If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)
Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;
and then fetch the query results.
If this does not answer your questions please provide some clarifications.
Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
$conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
?>
Read more here.

PHP SQL Truncate

I'm having a problem trying to truncate the 'requestID' field from my requests table.
This is my code.
<?php
include 'mysql_connect.php';
USE fypmysqldb;
TRUNCATE TABLE requestID;
echo "Request ID table has been truncated";
?>
I'm using server side scripting so no idea what error is coming back.
Anyone got an idea?
You aren't executing queries, you're just putting SQL code inside PHP which is invalid. This assumes you are using the mysql_*() api (which I kind of suspect after viewing one of your earlier questions), but can be adjusted if you are using MySQLi or PDO.
// Assuming a successful connection was made in this inclusion:
include 'mysql_connect.php';
// Select the database
mysql_select_db('fypmysqldb');
// Execute the query.
$result = mysql_query('TRUNCATE TABLE requestID');
if ($result) {
echo "Request ID table has been truncated";
}
else echo "Something went wrong: " . mysql_error();
Take a look at the function mysql_query which performs the query execution. The code to execute a query should look something like this.
$link = mysql_connect('host', 'username', 'password') or die(mysql_error());
mysql_select_db("fypmysqldb", $link) or die(mysql_error());
mysql_query("TRUNCATE TABLE requestID", $link) or die(mysql_error());
mysql_close($link);

Default Field Value to MySQL Database

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) ";

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