I am trying to delete a specific entry in my MYSQL Database.
Database: PhotoID, IDCount, UserID.
This is my code for deleting a photo depending on the ID.
function delete($IdPhoto) {
$result = query("DELETE from photos WHERE IdPhoto='%d'", $IdPhoto);
if (!$result['error']) {
// if no error occured, print out the JSON data of the
// fetched photo data
print json_encode($result);
} else {
//there was an error, print out to the iPhone app
errorJson('Photo stream is broken');
}
}
This is paired with an iOS Application that grabs the current photos ID at all times. When a button is pressed, the delete function in the API will trigger. This doesn't seem to work though.
The following query works (specific ID):
$result = query("DELETE from photos WHERE IdPhoto=10");
Any help would be appreciated. The goal is to delete the photo depending on the $IdPhoto we grab in the iOS Application.
Try this:
$result = query("DELETE from photos WHERE IdPhoto={$IdPhoto}");
did you tried this :
$result = mysql_query("DELETE from photos WHERE IdPhoto='$IdPhoto' ");
you should use mysql_query
This
..IdPhoto='%d'
should be
..IdPhoto=%d
Since a int value shouldn't be surrounded by quotes
The "=" will only compare two int values or double values. Make sure you are comparing the type int. Thus your delete function should pass an int, otherwise you might need a function like getIntvalue() to extract the int value.
Related
I'm have a live website that uses PHP and a mySQL database. I'm looking to use d3 to create a few visualizations. But I don't know how to alter the data as it is stored in the SQL database before directly encoding it in a JSON for d3. My PHP:
$activity_array = $array;
while ($activity = mysqli_fetch_assoc($get_all_activities)) {
// $user_name = find_user_by_id($activity['user_id']);
// echo $user_name['last_name'];
$activity_array[] = $activity;
}
echo json_encode($activity_array);
However, due to how my mysql database is set up, users are set up as numbers, so that what I get back in the JSON looks like:
[{"id":"93","date":"2020-05-01","user_id":"37","user_notes":"This user has blah blah."},...]
When I use this JSON to generate a graph in d3, I want it to show the actual user's name, not "37". In the PHP code above I commented out the query I have to get the user's name from their user_id, but then I have no idea how to get that into my JSON.
Thanks for the help!
You just need to modify the appropriate entry in the $activity array with the username retrieved by the second query:
$activity_array = $array;
while ($activity = mysqli_fetch_assoc($get_all_activities)) {
$user_name = find_user_by_id($activity['user_id']);
$activity['user_id'] = $user_name['last_name'];
$activity_array[] = $activity;
}
echo json_encode($activity_array);
It would however probably be easier to modify the $get_all_activities query to JOIN to the users table and fetch the username in that query directly.
I am working on an android app which uses APIs made with php. Here, i am dynamically creating columns and their values.
I am verifying the API via postman and a strange thing happens every time, While looping through the Json Object what i am doing is first creating column and then inserting its values.
The problem is only the 1st iteration saves the element and rest of them only creates the column but does not insert the values. I don't know if i am doing anything wrong, below is my php code.
<?php
include("connection.php");
$data = file_get_contents('php://input');
$json_data = json_decode($data);
foreach($json_data as $key => $val) {
$column_name = $key ;
$c_column_name = preg_replace('/[^a-zA-Z]+/', '', $column_name);
$column_value = $val ;
$table_name = "test2";
$email = "ht#t.com";
$result = mysqli_query($conn,"SHOW COLUMNS FROM $table_name LIKE '$c_column_name'");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;
if($exists) {
$query1 = "INSERT INTO $table_name($c_column_name)VALUES('$column_value') ";
$data0=mysqli_query($conn,$query);
if($data0)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Column existed, Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column existed, data not inserted."));
}
}
else{
$query2="ALTER TABLE $table_name ADD COLUMN `$c_column_name` varchar(50) NOT NULL";
$data1=mysqli_query($conn,$query2);
if($data1){
$query3="INSERT INTO $table_name($c_column_name)VALUES('$column_value')";
$data2=mysqli_query($conn,$query3);
if($data2)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column created but data not inserted."));
}
}
else
{
echo json_encode(array("success"=>"false - column creation","message"=>"Failed to create column.'$column_name', '$table_name', '$conn'"));
}
}
}
?>
Here is the Json Object through postman.
{"Shape":"rewq","Trans.No.":"yuuiop","Color":"qwert"}
Please help me with this, any help or suggestions are highly appreciated.
The second column name is Trans.No. which contains a dot, this is why it fails, probably you have an error as a result which prevents further columns from being created.
I think it would be much better to have a table with this structure:
attributes(id, key, value)
and whenever a key-value pair is received, you just insert/update it, depending on the logic you need to be executed. Your current model will create a separate row for each attribute, which is probably not what you want to achieve.
EDIT
Based on the information received in the comment section I reached the following conclusion:
You could create the missing columns first and then generate the insert statement with all the columns, having a single insert.
But it would be better to not create a separate column for each value, as the number of columns could quickly get out of hand. Instead you could have a table:
myentity(id, name)
for storing the entities represented by the JSON and
attributes(id, myentity_id, key, value)
for storing its attributes. This would be a neat schema with all the dinamicity you could want.
I have a table where I store all the machine details, I need to delete all data and drop all tables of a specific user.
I'm trying to DROP tables based on the result from Select query, but it's not working as it is inside WHILE of SELECT query. Kindly help me with this.
$sql="SELECT M_ID FROM machine_details WHERE Username='".$inname."'";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
$delmid=$row['M_ID'];
$delsta=$delmid."_status";
$delpar=$delmid."_parameter";
$sql1="DROP TABLE IF EXISTS $delpar, $delsta";
if(!mysqli_query($conn,$sql1))
{
echo "Error in drop".mysqli_error($conn);
}
else
{
$sql2="DELETE FROM machine_details WHERE M_ID=".$delmid;
if(!mysqli_query($conn,$sql2))
{
echo "Error in machine delete".mysqli_error($conn);
}
}
I'm not getting any errors from PHP or MariaDB, but the code doesn't DROP the table(It exists in phpmyadmin).
Any alternate or more efficient methods are also welcome.
UPDATE : The above code works perfectly fine now, kindly see the edit logs for better understanding about the issue I faced.
ID is int type! Dont place it in quotes. Right method is:
$sql2="DELETE FROM machine_details WHERE M_ID=".$delmid;
Try with Following Code to Delete.
For Delete you can use this code.
<?php
//delete.php
include("connection.php");
if(isset($_POST["_id"]))
{
$query = "DELETE FROM app WHERE _id = '".$_POST["_id"]."'";
if(mysqli_query($connection, $query))
{
echo 'Data Deleted';
}
}
?>
Note: Don't Delete any user data from the table, because if you need any history or detail report you can use this, for this you can put one flag.
Just remove the backquotes(`)
With its use M_ID is being converted to String type. Which should not happen... Because the primary key is int in your case
DELETE FROM machine_details WHERE M_ID=".$delmid;
I am trying to set an int value from an sql query. In my ios app I can assign an int value to a photo ID, store it and retrieve it fine. The problem comes if I want to overwrite the photo with a new jpg but still using the existing IdPhoto and therefore the same filename, e.g. 1.jpg. I first check whether the user exists. If so I update the photo (this is where I need to set the IdPhoto) otherwise I create a photo with a new ID (works fine).
function uploadDetails($Name, $Location, $photoData, $IdPhoto) {
$uploads = query("SELECT Name, IdPhoto FROM users WHERE Name = '%s' limit 1",$Name);
if (count($uploads['result'])>0) {
$result = query("UPDATE users SET Name='$Name', Location='$Location', IdPhoto='$IdPhoto' WHERE Name = '%s'", $Name);
//Need to define IdPhoto from users table
if (move_uploaded_file($photoData['tmp_name'], "icons/".$IdPhoto.".jpg")) {
thumb("icons/".$IdPhoto.".jpg", 180);
//I can print out confirmation to the iPhone app
print json_encode(array('$IdPhoto'=>$IdPhoto));
} else {
//print out an error message to the iPhone app
errorJson('Upload on server problem');
};
}
else {
if ($photoData['error']==0) {
$result = query("INSERT INTO users(Name, Location) VALUES('%s','%s')", $Name, $Location);
if (!$result['error']) {
// fetch the active connection to the database (it's initialized automatically in lib.php)
global $link;
// get the last automatically generated ID in the table
$IdPhoto = mysqli_insert_id($link);
if (move_uploaded_file($photoData['tmp_name'], "icons/".$IdPhoto.".jpg")) {
thumb("icons/".$IdPhoto.".jpg", 180);
print json_encode(array('successful'=>1));
} else {
errorJson('Upload on server problem');
};
} else {
errorJson('Upload database problem.'.$result['error']);
}
}
}
}
So the problem lies in the first part of the code where I need to update the photo but still use the same IdPhoto
EDIT
The piece of code I needed was as follows:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT IdPhoto FROM users WHERE Name = '$Name'"));
$IdPhoto = $getID['IdPhoto'];
Although I got to the answer eventually myself, I appreciate feedback of how to phrase questions better in future. And writing out the full code probably helped me look at the bigger picture and see where I was going wrong.
Your question is extremely vague but I'm going to take the following assumptions:
Your query will only ever return a single record
You are using MySQLi
Once you have run the query and stored the results into $result you can use the following code to get the IdPhoto:
//Store a row from results into variable
$row = $result->fetch_assoc();
//Store IdPhoto into variable
$IdPhoto = $row['IdPhoto'];
Note: Also you are selecting Name from the database when you already have the Name since you're using it to fetch the record
So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
$dvalue = mysql_fetch_array($dvalue);
$dvalue['value'];
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Array".
Please help me out.
This is because you can't just echo an array. You need to use functions like var_dump(); or print_r();
looks like you have more than one row in your table matching criteria. Try using while loop to retrieve data.
while($row = mysql_fetch_assoc($dvalue)){
//$row['value'];
}