cannot delete record with php script - php

when i go to produkdelete.php i can view the record that i want to delete, but when i confirm to delete there is no deleted record
this is my script :
$key = #$_GET["key"];
case "I": // Get a record to display
$tkey = $key;
$strsql = "SELECT * FROM `produk` WHERE `id`=".$tkey;
$rs = mysql_query($strsql, $conn) or die(mysql_error());
if (mysql_num_rows($rs) == 0)
{
ob_end_clean();
header("Location: "."produklist.php");
}
$row = mysql_fetch_assoc($rs);
$x_id = $row["id"];
$x_kdprod = $row["kdprod"];
$x_namaprod = $row["namaprod"];
$x_diskripsi = $row["diskripsi"];
$x_harga = $row["harga"];
mysql_free_result($rs);
break;
case "D": // Delete
// Open record
$tkey = $key;
$strsql = "DELETE FROM `produk` WHERE `id`=".$tkey;
$rs = mysql_query($strsql, $conn) or die(mysql_error());
mysql_free_result($rs);
mysql_close($conn);
ob_end_clean();
header("Location: produklist.php");
break;
the key variable is send from "produkdelete.php?key=".urlencode($row["id"]);
and everytime i run this the output just come like this :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=' at line 1

In SQL Management Studio this won't run.
$strsql = "DELETE FROMprodukWHEREid=".$tkey;
Lose the ` and it should execute.
With PDO for added security (explanation below)
$myServer = "put url to your server here";
$myDB = "put name of database here";
$name = "login name db";
$pw= "password db";
try
{
$dbConn = new PDO("mysql:host=$myServer;dbname=$myDB", $name, $pw);
}
catch( PDOException $Exception )
{
//Uncomment code to show error
//var_dump($Exception);
}
function doPDOQuery($sql, queryArguments = array())
{
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArguments );
}
$sql = 'SELECT * FROM produk WHERE id= :id';
doPDOQuery( $sql, array(":id" -> $tkey) );
This should execute on your server. It's using the PDO module for creating prepared queries. That means that the query itself is created by the database-driver itself. This prevents SQL-injection. This is a reason why MySQL_functions are deprecated.
For delete, update and insert the code above is sufficient. You need to do a $sth->fetchAll() to retrieve rows from a select.
Why are PHP's mysql_ functions deprecated?

Related

PHP mysqli_fetch_assoc not doing returning correct value

I have an old PHP code that has mysql in it.
It gets an array from a SELECT statement, adds it to a JSON object, as a property and echoes the encoded JSON.
I changed it around to use mysqli, but when I try to get the rows, and create an array out of them, it just returns nothing.
Here's the old mysql code:
$con = mysql_connect('host','account','password');
if (!$con)
{
//log my error
};
mysql_select_db("database_name", $con);
mysql_set_charset('utf8');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$query = mysql_query($sql);
$results = array();
while($row = mysql_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Version1: Here's the new one that I tried writing:
$con = mysqli_connect('host','account','password','database_name');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$results = array();
if($result=mysqli_query($con, $sql))
{
while ($row=mysqli_fetch_assoc($result))
{
$results[] = $row;
}
return $results;
}
else
{
//error
}
Version2: Second thing I tried, which only returns 1 ROW:
...same as above until $sql
if($result=mysqli_query($con,$sql))
{
$row=mysqli_fetch_assoc($result);
return $row;
}
Version3: Or I tried to completely mirror the mysql structure like this:
$sql = "SELECT ...";
$query = mysqli_query($con, $sql);
$results = array();
while($row = mysqli_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Wrapping the resulting array into the JSON:
$obj = new stdClass();
$obj->Data = $results;
$obj->ErrorMessage = '';
die(json_encode($obj)); //or echo json_encode($obj);
None of the mysqli version are working, so I was thinking there might be an important change in the way these arrays are created.
Any tips on what could be wrong on the first mysqli example?
With Version2 I can tell that the SQL connection is there, and I can at least select a row. But it's obviously only one row, than it returns it. It makes me think, that building up the array is the source of the problem, or it's regarding the JSON object...
LATER EDIT:
OK! Found a working solution.
ALSO, I played around with the data, selected a smaller chunk, and it suddenly worked. Lesson from this: the function is not responding the same way for 40 rows or for 5 rows. Does it have something to do with a php.ini setting? Or could there be illegal characters in the selection? Could it be that the length of a 'Note' column (from the db) is too long for the array to handle?
Here's the working chunk of code, that selects some rows from the database, puts them into an array, and then puts that array into an object that is encoded into JSON at the end, with a statusmessage next to it. Could be improved, but this is just for demo.
$con = mysqli_connect('host','username','password','database_name');
if (!$con)
{
$errorMessage = 'SQL connection error: '.$con->connect_error;
//log or do whatever.
};
$sql = "SELECT Field1 as FieldA, field2 as FieldB, ... from Table where ID='something'";
$results = array();
if($result = mysqli_query($con, $sql))
{
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
else
{
//log if it failed for some reason
die();
}
$obj->Data = $results;
$obj->Error = '';
die(json_encode($obj));
Question is: how can I overcome the issue regarding the size of the array / illegal characters (if that's the case)?
Your "Version 1" seems to be correct from a PHP perspective, but you need to actually handle the errors - both when connecting and when performing the query. Doing so would have told you that you don't actually query a table, you're missing FROM tablename in the query.
Use mysqli_connect_error() when connecting, and mysqli_error($con) when querying to get back the actual errors. General PHP error-reporting might also help you.
The code below assumes that $parameter is defined prior to this code.
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error());
$sql = "SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = '".$parameter."'";
$results = array();
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
return $results;
} else {
return mysqli_error($con);
}
Error-reporing
Adding
error_reporting(E_ALL);
ini_set("display_errors", 1);
at the top of your file, directly after <?php would enable you to get the PHP errors.
NOTE: Errors should never be displayed in a live environment, as it might be exploited by others. While developing, it's handy and eases troubleshooting - but it should never be displayed otherwise.
Security
You should also note that this code is vulnerable to SQL-injection, and that you should use parameterized queries with placeholders to protect yourself against that. Your code would look like this with using prepared statements:
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error())
$results = array();
if ($stmt = mysqli_prepare("SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = ?")) {
if (mysqli_stmt_bind_param($stmt, "s", $parameter)) {
/* "s" indicates that the first placeholder and $parameter is a string */
/* If it's an integer, use "i" instead */
if (mysqli_stmt_execute($stmt)) {
if (mysqli_stmt_bind_result($stmt, $field1, $field2) {
while (mysqli_stmt_fetch($stmt)) {
/* Use $field1 and $field2 here */
}
/* Done getting the data, you can now return */
return true;
} else {
error_log("bind_result failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("execute failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("bind_param failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("prepare failed: ".mysqli_stmt_error($stmt));
return false;
}
References
http://php.net/mysqli.prepare
How can I prevent SQL injection in PHP?

php mysql query throwing errors

what is wrong with this script? it keeps giving my erros but will not tell me what is wrong
I need this to lookup channel number from the item number passed in url. then echo the channel number
<?php
$id = $_GET['item'];
if (!$link = mysql_connect('server', 'user', 'pass')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('xmlrpc', $link)) {
echo 'Could not select database';
exit;
}
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'")or die(mysql_error());
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['channel'];
}
mysql_free_result($result);
?>
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'") or die(mysql_error());
To
$sql = "SELECT channel FROM channels WHERE item = '".$_GET['item']."'";
As a sidenote do not use mysql_ functions, they became obsolete (PHP 5.5). Use PDO instead for example, as it stands your code is vulnerable to SQL injections.
when item is already declared as a variable $id
$id = $_GET['item'];
you could already use it as a variable in your mysql
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'")or die(mysql_error());
change it into
$sql="SELECT * FROM channels WHERE item ='$id'";

Get mysql result and using it in a subsequent insert command within the same script

So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.

How to display only result in page

I have a big problem. I wrote a simple $_GET system
$query = mysql_query("SELECT * FROM `users`");
while ($row = mysql_fetch_array($query)) {
if($_GET['user'] == $row['user_seo']) {
echo 'user exists';
} else {
echo 'No users found';
}
}
If user don't exists in table it display 'No users found' otherwise it display No users found user exists No users found. 2 times it display "No users found" but user exists with that seo in database table. Thanks.
database screen http://prntscr.com/2ddqu4
You are looping over all your users so you will get multiple messages.
You should add a WHERE condition to your query to check only for the required user and switch to PDO or mysqli with prepared statements.
Something like (in PDO):
$query = 'SELECT * FROM `users` WHERE `user_seo`=:user';
$db->prepare($query);
$db->execute(array(':user' => $_GET['user']));
// etc.
Try replacing mysql_fetch_array with mysql_fetch_assoc
Also I would strongly recommend using either PDO or mysqli and prepared statements
Safely find the user with mysqli:
if (isset($_GET['user'])) {
$user = $_GET['user'];
$connection = mysqli_connect($Host, $Username, $Password) or die(mysqli_error());
mysqli_select_db($connection, $database) or die(mysqli_error());
$user = mysqli_real_escape_string($connection, $user);
if (!is_numeric($user)) {
$user = "'$user'";
}
$sql = "SELECT * FROM `users` WHERE `user_seo`=$user;";
$result = mysqli_query($connection, $sql);
if ($result) {
$user = mysql_fetch_assoc($result)) {
if ($user) {
// User found
// Do something with info like:
$userName = $user['name'];
} else {
// User NOT found
}
mysql_free_result($result);
} else {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
}
You better may use an sql like this:
SELECT * FROM users WHERE user_seo='".$_GET['user']."'; And forget about looping all the rows.
EDIT: but better use PDO or Mysqli and prepared statements

I'm a little confused, PHP says $results is a non-object of the mysqli class

I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();

Categories