Create SQL Table and Populate it - php

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

Related

DELETE and UPDATE with mysql and 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. :)

update query for unique column

This query change only the name, I want change the username too...
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'mydb');
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
$query = "CREATE TABLE users (id INT UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, name VARCHAR(50) NULL, PRIMARY KEY (id), UNIQUE(username)) ENGINE = MyISAM";
if ($mysqli->query($query)) {
$query = "INSERT INTO users (id, username, name) VALUES (1, 'user1', 'name1')";
if ($mysqli->query($query)) {
$query = "UPDATE users SET username = 'user_1', name = 'name_1' WHERE id = 1";
if ($mysqli->query($query)) {
$query = "SELECT id, username, name FROM users WHERE id = 1";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo 'id = ' . $row['id'] . ', username = ' . $row['username'] . ', name = ' . $row['name'];
}
$result->free();
}
}
}
$mysqli->close();
?>
In this example:
Started as [1, user1, name1]
Changed to [1, user1, name_1]
Instead of [1, user_1, name_1]
There is no way to update UNIQUE columns?
Your script won't run (table creation) when reloading it (only on the first/initial execution), since your table already exists and MySQL is failing on you silently, since you're not checking for errors.
Sidenote: You may have slightly modified your script and then ran it after.
Having included the following debugging code at the top of your script, you would have been thrown errors about it and is crucial when debugging during development before going live:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code
Therefore, you can only run that script once. You need to either test it again with a new table name, or remove the table creation code.
You can also check if the table exists.
References:
http://dev.mysql.com/doc/refman/5.7/en/create-table.html
https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html
A quick example:
CREATE TABLE IF NOT EXISTS `test`
You can also use UPDATE IGNORE table ... syntax (not to be used with your present table creation codes though):
http://dev.mysql.com/doc/refman/5.7/en/update.html
and INSERT IGNORE INTO table
https://dev.mysql.com/doc/refman/5.5/en/insert.html
Now your entire code (as a rewrite) would look like this:
$query = "CREATE TABLE IF NOT EXISTS users
(id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
name VARCHAR(50) NULL,
PRIMARY KEY (id),
UNIQUE(username))
ENGINE = MyISAM";
if ($mysqli->query($query)) {
$query = "INSERT IGNORE INTO users (id, username, name) VALUES (1, 'user1', 'name1')";
if ($mysqli->query($query)) {
$query = "UPDATE IGNORE users SET username = 'user_1', name = 'name_1' WHERE id = 1";
if ($mysqli->query($query)) {
$query = "SELECT id, username, name FROM users WHERE id = 1";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo 'id = ' . $row['id'] . ', username = ' . $row['username'] . ', name = ' . $row['name'];
}
$result->free();
}
}
}
There is no way to update UNIQUE columns?
Yes, with UPDATE IGNORE table ....
http://dev.mysql.com/doc/refman/5.7/en/update.html
However and with your present code, it will fail on the INSERT, since that is being executed before the UPDATE.
Think logically and you will see what is going on here.

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

php - duplicate entry

what should do if the entry are doubled?
<?php
require_once('auth.php');
session_start();
$exam = $_SESSION['exam'];
$subject_id = $_SESSION['exam'];
$_SESSION['sub'] = $subject_id;
$subject_title = $_POST['subject_title'];
$subject_description = $_POST['subject_description'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_compre', $con);
$sql = "INSERT INTO examsubjectrecord_table(subject_id , subject_title ,
subject_description)
VALUES ('$subject_id','$subject_title', '$subject_description')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
header("location: addsubject.php?exam=".$exam ."");
}
?>`
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\compre\admin\addsubjectacc.php on line 4
**Error: Duplicate entry '1' for key 'PRIMARY'**
It depends on yout application business-logic.
You can notify a user about a duplicated entry or silently update information with INSERT ... ON DUPLICATE KEY UPDATE ... SQL statement.
In your database you have a primary key of subject_id which cant have duplicates.
If you need to have duplicates in the subject_id column then you should add a column and set it as a primary key in your database. For example add another column unique_id and set it to auto_increment and as a primary key for row identification.
Basically, you'll first want to check if the value you're trying to insert into your primary key field already exists.
So if you primary key field is subject_id, you'd need to check if that already exists by doing a select query followed by PHP's mysql_num_rows function. For example:
$subject_id = 1337;
$check = mysql_query("SELECT `subject_id` FROM `examsubjectrecord_table` WHERE `subject_id`=" . $subject_id);
// See if anything was returned
if(mysql_num_rows($check) > 0) {
// We have something with this subject_id already!
echo "Cannot insert duplicate subject!";
} else {
// All clear, run your INSERT query here
}
Which column is your primary key? I'm going to assume that's subject_id. This needs to be unique for each row in your table. The easiest way to ensure this is to use AUTO_INCREMENT and then avoid inserting the subject_id at all. It will be assigned automatically.
If you need to find out what the ID of new subjects is, you can use mysql_insert_id.

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