Why is my database table not updated after this query? - php

I am using a dedicated server through 1 and 1 and the PHP code as below will not insert the data into the database.
All connections to database are correct.
$id = $_REQUEST['id'];
$content = $_REQUEST['content'];
mysql_query("UPDATE `content` SET `content` = '$content' WHERE `id`='$id'");
When I test on my local server all works fine, there is something about the server that will not allow me to upload. I am connecting using a very general method
$connection = mysql_connect("localhost",
"root",
"password");
mysql_select_db("dbname", $connection);

1) Turn on error reporting by putting this on the top of your PHP script:
error_reporting(E_ALL);
2) Run your script. Any errors? If yes, proceed according to the error message you get.
3) Double check that your variables are actually defined (you are getting them from the request, you cannot be sure request actually contains values you are trying to use).
4) Your SQL query is very dangerous. Use mysql_real_escape_string() or prepared statements. Don't put quotes around integer values.
5) Edit your script to look more like this:
error_reporting(E_ALL);
$id = (isset($_REQUEST['id']) && !empty($_REQUEST['id'])) ? $_REQUEST['id'] : NULL;
$content = (isset($_REQUEST['content']) && !empty($_REQUEST['content'])) ? $_REQUEST['content'] : NULL;
try{
if(NULL === $id){
throw new Exception('$id is NULL');
}
if(NULL === $content){
throw new Exception('$content is NULL');
}
$id = mysql_real_escape_string($id);
$content = mysql_real_escape_string($content);
$sql = "UPDATE content SET content = '$content' WHERE id = $id";
// connect to database
// ...
mysql_query($sql);
}catch(Exception $e){
echo '<p style="color: red;">',$e->getMessage(),'</p>';
}

Ddebugging for beginners...
You haven't posted any errors, is error reporting turned off? Debugging is much easier with error reporting turned on.
error_reporting(E_ALL);
We'll also want to see what the actual query we're trying to run in the database. Perhaps the variables haven't been properly escaped (Contains illegal characters).
$query = "UPDATE table SET name='$name' where id='$id'";
echo $query;
mysql_query($query);
My guess is that you have to mysql_real_escape_string(); both variables.
Also you pass $id as a string, it's probably an integer.

You're mishandling transactions.

Related

Cant access data in database, mysqli functions do not work but show no error

-I want to get the Id of user so I can show a welcome message in his profile but I cant seem to return the id. Maybe it is a problem in the query but when I run the code it only shows: "Error:" so I cant seem to find what is wrong.
-I have tried different sintaxes for the queries and they also work when testing them in phpmyadmin with concrete values.
-"Emri" is firstname in my language.
My db connection:
$dbc = mysqli_connect('127.0.0.1', 'root', '', 'oms_db');
my fuctions in a file fuctions.php:
ini_set ("display_errors", "1");
error_reporting(E_ALL);
include('dbc.php');
function getId($dbc, $username)
{
$query = "SELECT id FROM user WHERE username='.$username.'";
$q = mysqli_query($dbc, $query);
if($r = mysqli_fetch_assoc($q)){
return $r[id];
}
else {
echo "Error: ".mysqli_error($dbc);
}
}
function getData($dbc, $id, $data)
{
$q = "SELECT * FROM user WHERE id='.$id.'";
$r = mysqli_query($dbc, $q);
$array = mysqli_fetch_assoc($r);
echo $array[$data];
}
How I called the fuctions:
if(isset($_SESSION['username'])) {
if(!isset($_GET['id'])){
$userId = getId($dbc, $_SESSION['username']);
}
echo "Welcome to profile, ".getData($dbc, $userId, 'emri');
I have read 10 or more posts in stakoverflow but haven't found a solution. I think it is a problem with phpmyadmin or maybe queries dont work within a function.
The problem here is with the quotes and concatenates in
WHERE username='.$username.'";
either remove the dots
WHERE username='$username'";
or add double quotes
WHERE username='".$username."'";
since we are dealing with strings
https://dev.mysql.com/doc/refman/5.5/en/string-literals.html
Look into using prepared statements also:
https://en.wikipedia.org/wiki/Prepared_statement

Not adding values to database

I just created ajax function which sends data to php and php to database. Inserting to dotp_task_log table, works fine. But further, when I need to add data to dotp_tasks after adding to dotp_task_log, it isn't adding, and I cant find why... I get the Gerror, Here is my php file which adds data to database.
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task) VALUES ('$currentUser' , '$currentTasken')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("INSERT INTO dotp_tasks (task_percent_complete) VALUES ('$currentPercent') WHERE task_id='$currentTasken'" ) ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
As I stated in comments:
INSERT... doesn't have a WHERE clause. Error checking would have signaled the syntax error. INSERT ON DUPLICATE KEY does. You may have wanted to use UPDATE instead
$inss = mysql_query("UPDATE dotp_tasks
SET task_percent_complete = '$currentPercent'
WHERE task_id='$currentTasken'" );
References:
https://dev.mysql.com/doc/refman/5.0/en/update.html
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
Plus, do use error checking when testing:
http://php.net/manual/en/function.mysql-error.php
instead of echoing custom messages.
Add or die(mysql_error()) to mysql_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
Make sure your HTML form does hold a POST method and that all inputs bear the name attributes and no typos. Using error reporting, will signal that.
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Fred -ii- nailed it in his comment - you're using improper syntax in that query.
It looks like you want an update query, for example:
update dotp_tasks
set task_percent_complete = '$currentPercent'
where task_id = '$currentTasken'
Additionally - it's always best to avoid creating queries by formatting strings manually - you'll want to look into prepared statements to improve this code further.

how to insert value from radio button into mysql using php

i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

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