Make new users automatically follow a user - php

I am working on a php site with uses mysql as database, now my site is a social network like site where users follow each other, now if a user joins in he is following nobody so his stream remains empty so they leave the site quickly as well,i want users to be following my account account automatically when he joins in. Can you please tell me how to do it
here are the two tables
Table structure for table sn_users
CREATE TABLE IF NOT EXISTS `sn_users` (
`id` int(11) NOT NULL,
`username` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`password` varchar(225) NOT NULL,
`name` varchar(225) DEFAULT NULL,
`picture` varchar(100) NOT NULL,
`cover` varchar(100) DEFAULT NULL,
`job` varchar(225) DEFAULT NULL,
`address` varchar(225) DEFAULT NULL,
`date` int(11) NOT NULL,
`reg_id` text,
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
Table structure for table sn_follows
CREATE TABLE IF NOT EXISTS `sn_follows` (
`id` int(11) NOT NULL,
`from` int(11) NOT NULL,
`to` int(11) NOT NULL,
`date` int(11) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=74 DEFAULT CHARSET=utf8;

Run the query when the user get registerd.
<?
//Register query
$con = mysqli_connect("[HOST", "[USER]", "[PASS]", "[DB]");
$query1 = "INSERT INTO sn_users
(username, email, password, name, picture, cover, job, address, date, reg_id, active)
VALUES
('$username', '$email', '$password', '$name', '$picture', '$cover', '$job', '$address', 'date', 'reg_id', 'active')";
mysqli_query($con, $query);
//Auto follow query
$query2 = "INSERT INTO sn_follows
(`id`, `from`, `to`, `date`)
VALUES
([ID], '[NEW REGISTERD ACCOUNT], '[YOUR ACCOUNT]', '[DATE]')";
mysqli_query($con, $query2);
Hints:
Make of the field id in your database an auto_increment
Make sure you put a hashed password in the database

you need to do some modifications in your script.
1) get last inserted id of new registered user
2) insert that last id in sn_follows table with your id
this may elaborate flow
after your user register insert query get last id like below
example:
$sql = "INSERT INTO sn_users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$sqlfloow = "insert into sn_follows (from,to,date) values("your id",$last_id,date("Y-m-d H:i:s"))";
}

Related

mysqli_query not processing correctly

I'm setting up a small signup form that should be inserting the data to an existing table, return the unique ID and insert that value to a secondary table.
Currently, I presume that the the first query is not running because the unique ID returned is 0.
I've gone over this small portion of code, that works on all my other developments and can't seem to figure out where it's blocking.
mysqli_query ($db_conx, "INSERT INTO Users
(first_name, last_name, dob, email, user_type, company, start_date, end_date, create_timestamp, last_modify_timestamp, create_matricule, pwd_hash)
VALUES
('$first_name','$last_name','$dob','$email','$user_type','$company','$start_date','$end_date','$create_timestamp','$create_timestamp','$create_matricule','$password_hash')");
//Now select this user to retreive the matricule
$matricule = mysqli_insert_id($db_conx);
$sql2 ="INSERT INTO Permissions (matricule) VALUES ('$matricule')";
$query2 = mysqli_query($db_conx, $sql2);
if(!$query){
echo json_encode(['message'=>"Error : ". mysqli_error($db_conx), 'code'=>500]);
}
echo json_encode(['message'=>"Matricule ".$matricule." created", 'code'=>200]);
}
The console returns the following :
Object { message: "Matricule 0 created", code: 200 }
javascript.js:125:13
success javascript.js:126:13
ReferenceError: matricule is not defined[Learn More]
So therefore the creation to the second table works just fine but not the first.
My database is configured as follows:
CREATE TABLE `Users` (
`matricule` int(6) NOT NULL,
`first_name` varchar(35) NOT NULL,
`last_name` varchar(35) NOT NULL,
`dob` date NOT NULL,
`email` varchar(50) NOT NULL,
`user_type` varchar(3) NOT NULL,
`company` varchar(30) NOT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
`pwd_hash` varchar(500) NOT NULL,
`pwd_reset_hash` varchar(100) NOT NULL,
`otp_token` varchar(6) NOT NULL,
`create_timestamp` datetime NOT NULL,
`create_matricule` varchar(7) NOT NULL,
`manager_matricule` varchar(7) NOT NULL,
`sq_1` varchar(2) NOT NULL,
`sa_1` varchar(50) NOT NULL,
`sq_2` varchar(2) NOT NULL,
`sa_2` varchar(50) NOT NULL,
`last_modify_timestamp` datetime NOT NULL,
`last_modify_matricule` varchar(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Thanks for any input!!
I think you mispelled some variable names.
You are fetching $query2 :
$query2 = mysqli_query($db_conx, $sql2);
then checks $query :
if(!$query){
echo json_encode(['message'=>"Error : ". mysqli_error($db_conx), 'code'=>500]);
}
There is most probably an issued in the structure of you database or the JavaScript you haven't shared.
First, you must make the quotation marks as follows.
$sql="INSERT INTO Users (first_name) VALUES ('".$first_name."')";
Or you can use prepared statements

Triggers does cannot be created in phpMyAdmin

following is a trigger which I created in MySQL Workbench and the related tables are below as well. the trigger works perfectly in workbench but when I try to created the same trigger in phpMyAdmin, it gives me the follow error
Error
There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem
ERROR: Unknown Punctuation String # 11
STR: //
SQL: delimiter //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW
BEGIN
INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on,
modified_from) SELECT user_id, first_name, last_name, contact_no,
user_type, email, password, active, modified_by, modified_on,
modified_from FROM user WHERE OLD.user_id = user_id;
SQL query: Documentation
delimiter // CREATE TRIGGER log_user_delete BEFORE DELETE ON user FOR EACH ROW BEGIN INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from) SELECT user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from FROM user WHERE OLD.user_id = user_id;
MySQL said: Documentation
#1064 - 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 'delimiter //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW' at line 1.
what am I doing wrong?
2 tables :-
CREATE TABLE user (
user_id INT(11) NOT NULL AUTO_INCREMENT,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
contact_no VARCHAR(25) NOT NULL,
user_type VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
active INT(1) NOT NULL,
modified_by INT(11) NOT NULL,
modified_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
modified_from VARCHAR(20) NOT NULL,
PRIMARY KEY (user_id)
);
CREATE TABLE log_user (
log_id INT(11) NOT NULL AUTO_INCREMENT,
user_id INT(11) NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
contact_no VARCHAR(25) NOT NULL,
user_type VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
active INT(1) NOT NULL,
modified_by INT(11) NOT NULL,
modified_on DATETIME,
modified_from VARCHAR(20) NOT NULL,
log_modified_by INT(11) NOT NULL,
log_modified_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
log_modified_from VARCHAR(20) NOT NULL,
status VARCHAR(10) NOT NULL,
PRIMARY KEY (log_id)
);
Trigger :
DELIMITER //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW
BEGIN
INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from) SELECT user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from FROM user WHERE OLD.user_id = user_id;
UPDATE log_user SET status = 'DELETED' WHERE log_id = last_insert_id();
END;
// DELIMITER ;

How to check if column 1 has two different values for column 2

I am trying to make a INSERT by UNIQUE and I am getting stuck, What I want too know is how I would do is make it so Column A is ALWAYS UNIQUE unless Column C has two different values and then it will insert into the database a second row for Column A where Column C is different.
a|b|c
-----
1|2|3
2|4|5
1|6|7
So I am currently using this sql table
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL UNIQUE,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
With this query
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
It inserts the way I want so there is only 1 of each SteamID but it also will not insert if the same SteamID has two values for position.
EDIT:
What I have is a xml file I load up and insert data into the database based on the data in the xml file, What I need is below.
$xml = simplexml_load_file("players.xml");
foreach($xml->children() as $player)
{
$id = $player->attributes()->id;
$profile = new SteamProfile($id);
$name = mysql_real_escape_string($profile->getUsername());
$lastlogin = $player->attributes()->lastlogin;
$position = $player->lpblock->attributes()->pos;
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
so the xml file gets read and then the data in the file gets inserted into the database. sometimes the xml file would contain
<player id="76561197961716203" lastlogin="8/22/2014 10:49:28 PM">
<acl id="76561197961543041"/>
<acl id="76561197988417990"/>
<lpblock pos="273,93,-102"/>
<lpblock pos="1322,62,-1711"/>
</player>
at which point I would need a second row created for the second <lpblock pos=
So its currently inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
and it should be inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
|61|SwordFish |76561197961716203|1322,62,-1711|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
I'm not sure what you are trying to achieve, but you can set a UNIQUE restraint on a combination of columns, in your case SteamID and position:
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_combination_of_two_fields` (`SteamID`,`position`)
) ENGINE=InnoDB;
Thanks for you help Jeroen I did this and its working.
foreach($player->children() as $lpblock)
{
$position = $lpblock->attributes()->pos;
if(!empty($position))
{
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
}
However I would like all of the SteamID's inserted and not just the ones with a $position set. When I take this out and try it adds the correct rows but also adds another row with a blank $position as if there is a SteamID that's blank when there is none.
if(!empty($position)){
}

Why isn't my INSERT IGNORE code NOT working?

I am trying to avoid inserting duplicates records into my table by using the PRIMARY KEY and INSERT IGNORE methods. As suggested # http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm
I added the PRIMARY KEY to the tables definition as shown below:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("flightSched") or die(mysql_error());
mysql_query("CREATE TABLE Alteration(
id INT NOT NULL AUTO_INCREMENT,
timePeriod TIME default '00:00:00',
depOrArriv VARCHAR(9),
flightNo VARCHAR(9) NOT NULL,
airline VARCHAR(20),
dest VARCHAR(30),
origin VARCHAR(30),
depature VARCHAR(8),
don VARCHAR(10),
arrivalTime VARCHAR(8),
arrivalTimeSec VARCHAR(28),
status VARCHAR(15) NOT NULL,
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_name varchar(50) not null default '',
PRIMARY KEY (id, flightNo, status)
)")
or die(mysql_error());
echo "Table Created!";
Find below the INSERT IGNORE code:
mysql_query("INSERT IGNORE INTO Alteration
(depOrArriv, flightNo, airline, origin, don, arrivalTime, arrivalTimeSec, status, image_type, image, image_size, image_name)
VALUES('$depOrArriv', '$flightNo', '$airline', '$origin', '$don', '$arrivalTime', '$arrivalTime', '$status', '$image_type','$image', '$image_size', '$image_name' ) ");
// or die(mysql_error());
echo "Number of affected rows were: " . mysql_affected_rows();
While testing it I noticed that it STILL inserts duplicate records.
Why is it still doing this? Can anyone help me point out what is wrong?
Any help is greatly appreciated.
Looking forward to your feedback.
Your id column is auto incrementing which means each row is effectively unique when it is used in your key. You should inspect the data that you've inserted. You should see that each duplicate row actually has a separate and distinct id.
You can set a UNIQUE index on flightNo and status which would prevent the duplicate rows.
ALTER TABLE `Alteration` ADD UNIQUE (
`flightNo` ,
`status`
);
And then I would recommend just reducing your Primary Key to be id
UPDATE
As requested, this is a modified version of your code with a unique index used to prevent the duplicates:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("flightSched") or die(mysql_error());
mysql_query("CREATE TABLE Alteration(
id INT NOT NULL AUTO_INCREMENT,
timePeriod TIME default '00:00:00',
depOrArriv VARCHAR(9),
flightNo VARCHAR(9) NOT NULL,
airline VARCHAR(20),
dest VARCHAR(30),
origin VARCHAR(30),
depature VARCHAR(8),
don VARCHAR(10),
arrivalTime VARCHAR(8),
arrivalTimeSec VARCHAR(28),
status VARCHAR(15) NOT NULL,
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_name varchar(50) not null default '',
PRIMARY KEY (id),
UNIQUE KEY `flightNo` (`flightNo`,`status`)
)") or die(mysql_error());
echo "Table Created!";
mysql_query("INSERT IGNORE INTO Alteration (depOrArriv, flightNo, airline, origin, don, arrivalTime, arrivalTimeSec, status, image_type, image, image_size, image_name) VALUES('$depOrArriv', '$flightNo', '$airline', '$origin', '$don', '$arrivalTime', '$arrivalTime', '$status', '$image_type','$image', '$image_size', '$image_name' )");
echo "Number of affected rows were: " . mysql_affected_rows();

Query from contact table Insert to outbox table

Help me please.
I Want insert from contact table to outbox tabel.
contact:
CREATE TABLE `contacts`
(`id` int(11) NOT NULL auto_increment,
`name` varchar(25) NOT NULL,
`phone` varchar(20) NOT NULL,
`group_name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7;
INSERT INTO `contacts` VALUES (1, 'jala', '+60111', 'friends');
INSERT INTO `contacts` VALUES (2, 'jali', '+60222', 'friends');
INSERT INTO `contacts` VALUES (3, 'jalu', '+60333', 'friends');
INSERT INTO `contacts` VALUES (4, 'kada', '+60444', 'members');
INSERT INTO `contacts` VALUES (5, 'kadi','+60555','members');
INSERT INTO `contacts` VALUES (6, 'kadu', '+60666', 'members');
outbox:
CREATE TABLE `outbox`
(`id` int(11) NOT NULL,
`phone_number` varchar(20) NOT NULL,
`text` varchar(160) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;}
I Want insert to outbox tabel.
insert.php
$sql =mysql_query("SELECT phone
FROM contacts
WHERE group_name = 'member'");
while($data = mysql_fetch_array($sql))
{ $id= $data['id']; $phone= $data['phone'];(phone_number, text) VALUES('$phone','I LOVE YOU') }?>
INSERT INTO outbox (id,phone_number,text)
SELECT id,phone,'I LOVE YOU'
FROM contacts
WHERE group_name = 'member'
You need to use the INSERT...SELECT statement in your query. And also use PDO extention for this.
Example:
<?php
$sqlStatement = "INSERT INTO outbox (id, phone_number, text)
SELECT id, phone, ?
FROM contacts
WHERE group_name = ?";
$text = "I LOVE YOU";
$group_name = "member";
$stmt = $dbh->prepare($sqlStatement);
$stmt->bindParam(1, $text);
$stmt->bindParam(2, $group_name);
$stmt->execute();
?>
Remember to always sanitize your inputs.

Categories