Update rows in mysql via id - php

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

Related

Echoing Out A Mysql Query

Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}

PHP - MySql Database info not storing

I have been trying to figure this out for hours, I have created a database ( MySql/PHPMyadmin) and i am trying to get user input stored to be able to call back up, however the info is not making it/ saving it to the database, everything shows up okay except this part of code:
$registered = mysqli_affected_rows ($dbc);
echo $registered. "Row is affected";
when run gives me a display of -1 row, I believe this to be a big part of the problem as everything else seems to work okay. I am a complete beginner so could you guys tell me how the best way of debugging this is.
$dbc = $dbc = mysqli_connect ($hostname, $username, $password, $dbname) OR die("Could not Connect");
To input the data to the db i have the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$comments = $_POST ['Comments'];
if (!empty ($comments)){
include ('mysqldb.php');
mysqli_query ($dbc,"INSERT INTO 'User-Comments' (Comments) VALUES ('$comments')");
$registered = mysqli_affected_rows ($dbc);
echo $registered. "Row is affected";
}else {
echo "Nothing Submitted";
}
}
The line:
mysqli_query ($dbc,"INSERT INTO 'User-Comments' (Comments) VALUES ('$comments')");
should be:
mysqli_query ($dbc,"INSERT INTO `User-Comments` (Comments) VALUES ('$comments')");
Notice the change in the apostrophe character ( ` ) around your table name.
An excerpt from the documentation for function mysqli_stmt_affected_rows(): -1 indicates that the query has returned an error.
You should check the value returned by mysqli_query(). If it returns FALSE then you can get details about the reason (error message) by using function mysqli_error().

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

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

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