Deleteing doesn't work from database - php

I'm building a project with angular and php. I have a "file" table in my database that I can send file and retrieve all information that I need. I added a delete button but I don't know why it doesn't work. There are no errors in my console. Can someone please have a look at my code?
php for deleteing:
<?php
header('Content-Type: text/html; charset=utf-8');
$connect = mysqli_connect("localhost", "root", "", "hamatkin");
include_once 'file.php';
mysqli_query($connect, "SET character_set_client = utf8");
mysqli_query($connect, "SET character_set_connection = utf8");
mysqli_query($connect, "SET character_set_results = utf8");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//$customer = new Customer();
$data = json_decode(file_get_contents("php://input"));
$x = $data->reffer_customer_id;
$reffer_customer_id = $data->reffer_customer_id;
$del = "DELETE FROM file WHERE reffer_customer_id = " . $reffer_customer_id;
//echo $del;
mysqli_query($connect, $del);
$newURL = "/hamatkin/#/allPriceOffers";
header('Location: '.$newURL);
?>
Controller:
$scope.delete = function(deletingId, $index) {
$http.post('api/customers-tab/delete-priceOffer.php', { "reffer_customer_id" : deletingId })
.success(function(data) {
var arr = JSON.parse(JSON.stringify(data));
$scope.files = arr;
var arr2 = arr.split(",");
arr2.splice($index, 1);
$route.reload();
});
};
Html delete button:
<td><a ng-click="delete(x.reffer_customer_id, $index)" class="btn btn-primary btn-active">מחיקה</td>

First of all you should fix your HTML:
I don't know what you mean putting delete function on ng-click attribute, probably you want to use on-click instead? Correct me if I'm wrong
You have opened <a> tag, but </a> is absent
Corrected HTML button in <td> is:
<td><a on-click="delete(x.reffer_customer_id, $index); return false;" class="btn btn-primary btn-active">מחיקה</a></td>
In the second I propose to check your MySQL scheme of table file and be sure that you provide same type of refferal_customer_id.
For example, I've wondered that this should be numeric value, than:
<?php
header('Content-Type: text/html; charset=utf-8');
/*
* I propose to check all data before you will open connection to MySQL,
* because if data is not correct - connection will not be used
* I strongly propose to process errors in your client scripts
*/
$data = json_decode(file_get_contents("php://input"));
if (!isset($data) ||
!isset($data->reffer_customer_id) ||
!is_numeric($data->reffer_customer_id)
) {
echo 'Incorrect data specified';
exit;
}
/*
* Connecting
*/
$connect = mysqli_connect("localhost", "root", "", "hamatkin");
/*
* I don't know why you using it for delete query if your id is numeric
*/
mysqli_query($connect, "SET character_set_client = utf8");
mysqli_query($connect, "SET character_set_connection = utf8");
mysqli_query($connect, "SET character_set_results = utf8");
/*
* I don't recommend you to pass mysql connection error in raw format,
* because it can be used against you
* And don't forget to halt your script if error occurred
*/
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL";
exit;
}
/*
* Here your delete query
*/
$delId = mysqli_real_escape_string($connect, $data->reffer_customer_id);
if (!$delId) {
echo 'Incorrect id for delete query specified';
exit;
}
/*
* Don't forget to check errors
*/
if (!mysqli_query($connect, "DELETE FROM file WHERE reffer_customer_id = $delId")) {
echo "Failed to delete reffer_customer with id: $delId";
exit;
}
/*
* And close the connection
*/
mysqli_close($connect);
/*
* As for me: better to put next route into response for redirecting from client
* but I don't know what you will do with this, so, putting header
*/
header('Location: /hamatkin/#/allPriceOffers');

I think your query should be like these:
$del = "DELETE FROM file WHERE reffer_customer_id=".$reffer_customer_id." ";

Related

php parent page redirect twice after using header location

I am stuck with my php code. Parent php page reload again after header() works, Here is my code
<?php
$mysqli = new mysqli("localhost", "root", "root", "testing");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$sql ="update test set hit_count = hit_count+1";
$result = $mysqli->query($sql);
header('Location: http://www.google.com/');
die();
?>
Here some times i got 2 hit_count from db.
How it works, i added die() after header().
You should not output text before using header redirects as seen on the code below:
/* Select queries return a resultset */
if ($result = $mysqli->query($sql)) {
printf("updated");
}else{
echo "failed";
}

load default image if database connection fails

I am attempting to build a database driven site whereby images are loaded via a php script like so;
<img src="get_image.php?holderID=2">
I can get images to load from a folder outside the root directory when the database is accessible but I also want to be able to load a default image if there is a failure with making the database connection. The DB connection is initiated form a separate php connection file mysqli_template_connect.php;
DEFINE('DB_USER', 'someusername');
DEFINE('DB_PASSWORD', 'amnesia');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'template');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
and then config.inc.php sets some constants, one of which is for all DB connections;
define('MYSQL', '../../../dbconnect/mysqli_template_connect.php');
The get_image.php file then has a database connection conditional;
require('includes/config.inc.php');
REQUIRE(MYSQL);
$holderID = $_GET['holderID'];
if(!$dbc){
$image_name = 'img/unavailable.png';
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
}
else {
$query = "SELECT imageID FROM image_holder WHERE image_holderID = $holderID ";
$result = #mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$imageID = $row[0];
}
else {
$imageID = FALSE;
}
if ($imageID) {
$query = "SELECT file_name FROM image WHERE imageID = $imageID";
$result = mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$image_name = '../../../uploads/' . $row[0];
}
else {
$image_name = 'img/unavailable.png';
}
}
else {
$image_name = 'img/unavailable.png';
}
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
mysqli_close($dbc);
}
If I disable the MYSQL database in XAMP, the default image unavailable.png will not load even though the header and readfile section of code is virtually the same in the section of code that does work. I'm quite a newbie to all this so any ideas on loading the default image would be appreciated.
Depending on the database object you are using (MySQLi/PDO/etc), you can check if they connected. PDO returns a boolean that you can run against.
Since PDO is the most popular, I will provide an example of that. If you use something else, feel free to comment and I can clarify.
$connected = true;
if (!extension_loaded('PDO'))
{
$connected = false;
}
if (!extension_loaded('pdo_mysql'))
{
$connected = false;
}
try
{
$pdo = new PDO("mysql:host={$host};dbname={$db}", $user, $pass);
}
catch(PDOException $e)
{
$connected = false;
}
if(!$connected){ /* Load default image */ }
Note: just make sure you use the correct image headers.
Instead of
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Use
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
hopefully it should work..
I have similar code that do the almost the same thing.
I suspect it was the header, since I have a bit more info added to the header. No harm for you to try out.
header('Content-Description: File Transfer');
header('Content-Type: '. $file_content_type);
header('Content-Length: ' . filesize($file_full_path));
header('Content-Disposition: inline; filename=' . $file_name);
readfile($file_full_path);

Special characters with Ajax and MySQL

I have a MySQL database encoded with the default characterset UTF8. I have also a PHP code encoded with the same charset meta charset="UTF-8".
My connection to the database is configured to use UTF8 too
new PDO("mysql:host=" .$host. ";dbname=".$database,$username,$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
But I have a problem when I use Ajax to get the content of a textbox and insert it into the database.
If I do not use special characters it works fine but when I use a quote or something everything stops working.
I tried to use UTF8_encode and UTF8_decode but nothing changed
EDIT
PHP
...
<meta charset="UTF-8">
...
<textarea class="commentBox" id="<?php echo $id_case;?>"></textarea>
<button class="saveComment" id="<?php echo $id_case;?>"> Save comment </button>
//id_case is different for each textarea
Javascript
$('.saveComment').click(function()
{
var idComment = this.id;
var content = $('#'+idComment+'.commentBox').val();
add_comment(idComment, content);
});
function add_comment(case_id, content)
{
$.post("../functions/ajax/add_comment.php",
{
id_case: case_id,
content: content
},
function(data,status)
{
alert("It worked !");
console.log("Function add_comment : "+status);
});
}
add_comment.php
<?php
if(isset($_POST['id_case'], $_POST['content']))
{
$case = $_POST['id_case'];
$content = $_POST['content'];
}
else
{
echo "Error during sending data to [add_comment.php]";
}
if($db != null)
{
try
{
$sql = ("UPDATE cases SET progress_remarks = '$content' WHERE id_cases = $case");
$result = $db->exec($sql);
echo $content;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
else echo "Erreur interne (fill_progress.php)";
?>
My database connection is done somewhere else but looks like this
$this->con = new PDO("mysql:host=" .$host. ";dbname=".$database,$username,$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
when I use a quote or something everything stops working.
It is unclear whether the problem is (1) just an escaping issue, or (2) also a utf8 issue.
Since PDO has a builtin way to take care of escaping, use it:
$sql = ("UPDATE cases SET progress_remarks = ? WHERE id_cases = $case");
$result = $db->exec($sql, $content);
This is probably the preferred way to set the charset with PDO: $db = new PDO('dblib:host=host;dbname=db;charset=UTF-8', $user, $pwd);
meta charset="UTF-8" refers to the tag in HTML, not PHP or MySQL.
SHOW CREATE TABLE -- Is the column in question declared CHARACTER SET utf8?

Remove db $conn from MYSQLI query

I'm currently learning mysqli and systematically replacing all of my deprecated queries throughout my script.
I have this query:
<?php
$link = mysqli_connect("host", "user", "pass", "name");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM pins WHERE id='$pinDetails->id'";
$result = mysqli_query($link, $query);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$feature = $row['featured'];
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
Which I can echo throughout the page as <?php echo $row['date_featured']; ?>
My question is how do I rework the code to remove the connection? I don't want to keep connecting to the db in every query when I have a general connection include at the top of the page.
Actually you need connection for this page to operate based on your SQL database ,, can you explain more that what do you mean by removing connection
you can use INCLUDE();

Attempting to display an image in PHP from a MySQL database

I attempted to display the image using PHP with the following code
<?php
header('Content-type: image/png');
$port = "*";
$server = "*:".$port;
$dbname ="*";
$user = "*";
$conn = mysql_connect ("$server", "$user", "$pass") or die ("Connection
Error or Bad Port");
mysql_select_db($dbname) or die("Missing Database");
$speakerPic = $_POST['speakerPic'];
$query = "SELECT Speaker.speaker_picture AS image FROM Speaker JOIN Contact c USING(contact_id)
WHERE c.lname = '";
$query .= $speakerPic."';";
$result = mysql_query($query,$dbname);
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);
echo $result_data['image'];
?>
I keep on receiving this error, The image “.../query2.php” cannot be displayed because it contains errors.
Sorry to keep on bugging you guys, but can anyone tell what the problem is?
Not going to lie, there is a lot of bad with the OP code.
You should be pulling images from the database by id, not some string
You are not sanitizing the var being used in the query
You are not serving a default image if one doesn't exist
Also, I would suggest storing file uris in your database, not the actual image (blob). You should store a pointer to an image on your filesystem.
Not going to clean up the code too much, just make it less bad. I'd suggest something along these lines (untested):
// Utility.php
class Utility
{
/**
*
* #param mixed $id is abstract, could be name or an actual id
* #return string?
*/
public static function getImage($id)
{
try {
$port = "*";
$server = "*:".$port;
$dbname ="*";
$user = "*";
$conn = mysql_connect ("$server", "$user", "$pass");
if (!$conn) {
throw new Exception("Connection Error or Bad Port");
}
if (!mysql_select_db($dbname)) {
throw new Exception("Missing Database");
}
$query = "SELECT Speaker.speaker_picture AS image FROM Speaker JOIN Contact c USING(contact_id) WHERE c.lname = " . mysql_real_escape_string($id). ";";
$result = mysql_query($query,$dbname);
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);
if (!isset($result_data['image'])) {
throw new Exception('Image not found');
}
echo $result_data['image'];
} catch Exception($e) {
error_log($e->getMessage();
return file_get_contents('/path/to/some/default/image.png');
}
}
}
// image.php
require_once 'Utility.php';
header('Content-type: image/png');
ob_start();
Utility::getImage($_POST['speakerPic']);
$image = ob_get_flush();
echo $image;

Categories