DELETE and UPDATE with mysql and php - php

I am building gallery with categories and having problem with this subject.
Only 2 tables.
1st table has categories
Second table has photos data.
Second table has category_id from 1st table.
Pretty simple...
now when i delete the category i would like to update 2nd table with category_id = NULL ot = ''.
Is it possible ?
I tried using triggers but no success yet. getting syntax errors...
$sql = "
CREATE TRIGGER update_gal_items AFTER DELETE ON gallery_category
FOR EACH ROW
BEGIN
UPDATE gallery_photos SET photo_category='' WHERE photo_category=$id;
END
";
Any help please ?

You should rather apply Foreign key constraint:
ALTER TABLE gallery_photos
ADD FOREIGN KEY (photo_category) REFERENCES gallery_category(category_id)
ON DELETE SET NULL
Note that I am assuming category_id as field name in your parent table (gallery_category).
Now, if you still want to use Triggers, then define the following trigger on your gallery_category table:
DELIMITER //
DROP TRIGGER IF EXISTS gallery_category_delete_trigger //
CREATE DEFINER=`root`#`localhost` TRIGGER gallery_category_delete_trigger
AFTER DELETE ON gallery_category
FOR EACH ROW
BEGIN
UPDATE gallery_photos
SET photo_category = NULL
WHERE photo_category = OLD.category_id;
END //
DELIMITER ;

Well running to diffrent queries solves the problem...
global $conn;
if( isset( $_POST['cat_id'] ) ) {
$id = (int)$_POST['cat_id'];
}
$sql = "UPDATE `gallery_photos` SET `photo_category` = '' WHERE `photo_category` = ?";
$stmt1 = $conn->prepare( $sql );
$stmt1->bind_param('i', $id);
$stmt1->execute();
if (! $stmt1) {
$this->log->error ( "Mysqli prepare error: " . mysqli_error ( $conn ) );
throw new MysqliExecuteException ( "Mysqli error: " . mysqli_error ( $conn ) );
}
$sql_n = "DELETE FROM `gallery_category` WHERE `category_id` = '$id'";
$stmt = $conn->prepare($sql_n);
$stmt->execute();
if (! $stmt) {
$this->log->error ( "Mysqli prepare error: " . mysqli_error ( $conn ) );
throw new MysqliExecuteException ( "Mysqli error: " . mysqli_error ( $conn ) );
}
Thanks everyone for their time. :)

Related

Create Table In PDO Transaction

How can I fix this transaction so that the pdo query makes a new table in step #4?
The first three steps work, but I can't seem to get #4 to work.
STEPS
Finds a user with a chattingstatus of 0 in the database
Add a user into the database (with predetermined variables)
change the chattingstatus from 0 to 1 for both the user with a 0 status and the inserted user
4. Create a table with the id of both users as the title like this 2+13 (2 being the id and 13 being the id)
$userid = "123456";
$firstname = "Dae";
$oglang = "engs";
$status = 0;
$pdo->beginTransaction();
try{
// Find a user with a status of 0
$sql = "SELECT id FROM users WHERE chattingstatus = :status";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':status' => $status)
);
$freeuser = $stmt->fetchColumn();
//put the original user into the database with userid firstname and language
$sql = "INSERT INTO users (userid, firstname, oglang, chattingstatus) VALUES (:userid, :firstname, :oglang, :chattingstatus)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':userid' => $userid, ':firstname' => $firstname, ':oglang' => $oglang, ':chattingstatus' => 0)
);
$ogID = $pdo->lastInsertId();
// change the chattingstatus of 0 of the free user to 1
$sql = "UPDATE users SET chattingstatus = 1 WHERE id = :freeuser";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':freeuser' => $freeuser)
);
//query 3 CHANGE STATUS OF ORIGINAL USER from 0 to 1
$sql = "UPDATE users SET chattingstatus = 1 WHERE userid = :oguser";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':oguser' => $userid)
);
//query 4: Make a table between the 2 users with their IDs
$table = $freeuser."+".$ogID;
$sql ="CREATE table $table(
ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY,
Messages VARCHAR( 50 ) NOT NULL);";
$stmt = $pdo->exec($sql);
print("Created $table Table.\n");
$pdo->commit();
}
//Our catch block
catch(Exception $e){
//Print out the error message.
echo $e->getMessage();
//Rollback the transaction.
$pdo->rollBack();
}
Thanks in advance.
Since your table name includes the special character +, you need to put it in backticks to quote it.
$sql ="CREATE table `$table` (
ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY,
Messages VARCHAR( 50 ) NOT NULL);";
You'll need to remember to put backticks around the table name whenever you use it in other queries. If you insist on having per-user tables like this, you might want to use a different character to connect them, like underscore.
Creating table in transation doesn't work in MySQL:
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.
Source: https://www.php.net/manual/en/pdo.begintransaction.php

specifiy UNIQUE key to insert then to update the records

I am trying to update my records with this code below but a new record is being inserted in my table every time. How can I specify the UNIQUE key to reach my aim?
This is the whole code I have in my php script plus the connection.php file, which just contains the connection statement. In my mysql I just have one database where the route_4 table is being created. My databe just consists of the route_4 table.
PHP script:
<?php
$json = '{"latitude":83.16898451,"longitude":31.16561387,"route":4}';
$data = json_decode ( $json );
$route = "route_" . $data->{'route'};
$latitude = $data->{'latitude'};
$longitude = $data->{'longitude'};
require 'connection.php';
// check whether route's table exist.
$results = $con->query ( "SHOW TABLES LIKE'" . $route . "'" ) or die ( mysqli_error () );
if (($results->num_rows) == 1) {
//"UPDATE MyGuests SET lastname='Doe' WHERE id=2"
$sql = "INSERT INTO ".$route."(id, latitude, longitude, created_at)
VALUES( id, ? , ? , NOW() )
ON DUPLICATE KEY
UPDATE latitude = VALUES(latitude)
, longitude = VALUES(longitude)";
$stmt = $con->prepare($sql) or die ( $con->error );
$stmt->bind_param("ss",$latitude,$longitude);
$stmt->execute();
$stmt->close();
echo "Table exist";
} else {
$create = "CREATE TABLE " . $route . "
(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY UNIQUE,
latitude FLOAT(10,6) NOT NULL,
longitude FLOAT(10,6) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" ;
$stmt = $con->prepare($create) or die ( $con->error );
$stmt->execute();
$stmt->close();
echo "table was created";
}
Make below changes in you table structure
1) Remove the existing Unique key for column id
2) Add unique for latitude and ''longitude``
ALTER TABLE `db_name`.`route_4` ADD UNIQUE (
`latitude` ,
`longitude`
)
Once you make both latitude and longitude as group of unique key then your sql query will update record on duplicate entry else will insert.
Hope this helps

Create SQL Table and Populate it

I have a script that creates a SQL table for me as below
if ($con = mysql_connect($host, $username, $password)) {
if (mysql_select_db($db_name)) {
$sql = "CREATE TABLE ".$ac_system."_credits (id INT NOT NULL
AUTO_INCREMENT , PRIMARY KEY (id) , account_nr CHAR(10) , credits CHAR(10))";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
I would like to add another line/s to populate the above table with fixed information
ID - 1
Credits - 10
ACCOUNT_NR - 1
The above data is constant and doesn't need to be changed once the table is created I am not sure how to populate it in conjunction with the creation of the table. I can populate it from a seperate PHP script but need all to be done on one page
Maybe you should execute another one query just after successful table creation:
//some php code here
$insertSuccessful = true;
mysql_query( "INSERT INTO $ac_system ( account_nr, credits ) VALUES ( '1', '10' )", $sql );
// and here

PHP/MYSQL - Check whether it have duplicated record before inserting new record

Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source

Issues incrementing a field in MySQL/PHP with prepared statements

I have the following code which is supposed to increment a field value by 1 in a prepared PHP mysql statement:
function db_OP_doVote($pdo, $postid, $votetype)
{
$prepStatement = $pdo->prepare(
"UPDATE content_posts SET `:votetype` = `:votetype` + 1 WHERE `id` = :id"
);
$prepStatement->execute(array(':votetype' => $votetype, ':id' => $postid));
echo "Success";
}
This however, does nothing. No error is thrown back about incorrect SQL syntax and the script runs to completion, but my field does not update at all.
The values for this script are fed through a jQuery post() to this script:
//isset checking here
$postID = (int)$_POST['id'];
$voteType = $_POST['type'];
if ($voteType == "y")
{
$trueType = "v-cool";
}
elseif ($voteType == "m")
{
$trueType = "v-meh";
}
elseif ($voteType == "n")
{
$trueType = "v-shit";
}
else
{
die();
}
$db = db_Connect();
db_OP_doVote($db, $postID, $trueType);
Which also appears to filter the values and send them fine. I can't wrap my head around what the issue could be. The field being incremented is a BIGINT(20).
What am I missing?
EDIT: Solved the issue.
N.B's comment hit the nail on the head - binding the column name causes it to be quoted, which invalidates the query. Thanks!
you can't use binding for the field names.
from the question it seems that your setup is wrong.
you should have another table with votes and vote types as data.
You can't parameterize column names with PDO. What you can do is have hard-coded values (which you basically already have) and construct the SQL string accordingly. I would check this value in the actual function too though, just to be on the safe side:
function db_OP_doVote($pdo, $postid, $votetype)
{
if( !in_array( $votetype, array( 'v-cool', 'v-meh', 'v-shit' /*, etc. */ ), true ) )
{
throw new InvalidArgumentException( 'Unexpected $votetype: ' . $votetype );
// or simply return false perhaps
}
$sql = '
UPDATE content_posts
SET `' . $votetype . '` = `' . $votetype . '` + 1
WHERE `id` = :id
';
$prepStatement = $pdo->prepare( $sql );
$prepStatement->execute(array(':id' => $postid));
echo "Success";
}
However, this strategy suggests your database design could use a little more attention. The way you have it now, is that for every type of vote, you have a column. This is not really efficient and/or flexible database design. What happens if you get asked to add another type of vote?
I'd suggest adding another table, to be more flexible:
CREATE TABLE `content_post_vote` (
`content_post_id` int(11) NOT NULL,
`vote_type` enum('cool','meh','shit') NOT NULL, # using enum() to assure valid vote types
`votes` bigint(20) DEFAULT NULL,
PRIMARY KEY (`content_post_id`,`vote_type`)
)
Then your query would be something like:
$sql = '
INSERT INTO `content_post_vote` (`content_post_id`,`vote_type`,`votes`)
VALUES( :id, :votetype, 1 )
ON DUPLICATE KEY UPDATE `votes` = `votes` + 1
';
What this does is insert a vote if there is no record for a certain primary key (content_post_id,vote_type) yet, and else update the record with a vote if the record already exists.
Then to query the database for how many votes of a particular type a particular content_post has gotten, you do this:
$sql = '
SELECT `votes` # or perhaps more columns
FROM `content_post_vote`
WHERE `content_post_id` = :id AND
`vote_type` = :votetype
';

Categories