Query from contact table Insert to outbox table - php

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.

Related

mysql update table field from another table

i have these set of tables
CREATE TABLE `staff` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`uid` varchar(128) NOT NULL,
`name` varchar(128) NOT NULL,
`deptname` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `staff` (`id`, `uid`, `name`, `deptname`) VALUES
(1,'A100','John','Finance'),
(2,'A101','Joana','ICT'),
(3,'A103','Darrel','Maintenance'),
(4,'A104','Smith','HR');
CREATE TABLE `department` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`deptid` int(11) UNSIGNED NOT NULL DEFAULT '0',
`deptname` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `department` (`id`, `deptid`, `deptname`) VALUES
(1,'100','ICT'),
(2,'200','Finance'),
(8,'300','HR'),
(11,'400','Maintenance'),
(12,'500','Backup');
CREATE TABLE `new_staff` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`uid` varchar(128) NOT NULL,
`name` varchar(128) NOT NULL,
`deptid` int(11) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `new_staff` (`id`, `uid`, `name`, `deptid`) VALUES
(1,'A100','John','600'),
(2,'A103','Darrel','400'),
(3,'A104','Smith','300'),
(4,'A101','Joana','500'),
(5,'A105','Fran','800');
i would like to update the deptid field in the new_staff table to have the correct deptid as listed in the department table
in the new_staff table deptid are currently wrong for John and Joana
this is what i tried so far
// list all deptid exists
$result=$mysqli->query("SELECT deptid FROM department");
while ($rows=mysqli_fetch_array($result))
{$deptid[]=$rows['deptid'];}
$deptidarray = implode(', ', $deptid);
echo "<br>";
//echo "$deptidarray<br>";
$query=$mysqli->query("SELECT deptid from new_staff WHERE deptid not in ($deptidarray)");
echo "<br>";
$rowtotal = mysqli_num_rows($query);
if($rowtotal>0){
while ($row=mysqli_fetch_array($query))
{
$deptid=$row['deptid'];
// echo "$deptid,";
//$query=$mysqli->query("UPDATE new_staff set deptid='$deptid' WHERE ");
}
}
else
{
// not found
}
is this possible to do entirely in mysql?
UPDATE new_staff AS ns
JOIN staff AS s ON
ns.uid = s.uid // 1. Get same users from 2 tables
JOIN department AS d ON
s.deptname = d.deptname // 2. Get department
SET ns.deptid = d.deptid // 4. Update correct department id
WHERE ns.deptid != d.deptid; // 3. Get users where department is incorrect
Run SELECT query first before updating to verify the updates.
SELECT ns.*, d.deptid AS new_dept_id
FROM new_staff AS ns
JOIN staff AS s ON
ns.uid = s.uid
JOIN department AS d ON
s.deptname = d.deptname
WHERE ns.deptid != d.deptid;

Multiple mysql query in CI

There I have some multiple query and want to execute in Codeigniter.
Below are the code I tried.
function seememberfilter($course,$n)
{
$this->load->database();
$sql = array();
$sql[] = "CREATE TEMPORARY TABLE temp1";
$sql[] = "select id,rand, name,lname, email,phone from `member` where course like ('%$course%')";
$sql[] = "CREATE TEMPORARY table temp2";
$sql[] = "select distinct t.id,t.rand, t.name,t.lname, t.email,t.phone, a.quest_id from temp1 t left join assignment a on t.rand= a.rand";
$sql[] = "CREATE TEMPORARY table randid";
$sql[] = "select rand, quest_id from temp2 where quest_id=$n";
$sql[] = "select t.id,t.rand, t.name,t.lname, t.email,t.phone, r.quest_id from temp1 t left join randid r on t.rand= r.rand";
foreach ($sql as $sql_command)
{
if ($debugging == 0)
{
$this->db->query($sql_command);
}
elseif ($debugging == 1)
{
echo $sql_command;
}
}
return $query->result();
}
Above code is in model and below code is in Controller
public function assign(){
$this->load->model("user_model");
$course=$this->input->post('course');
$n=$this->input->post('id');
$data['sel'] = $this->user_model->seememberfilter($course,$n);
$this->load->view('assign',$data);
}
mysql query are executing well in phpmyadmin. I checked it
What I want: I want to execute mysql query in CI successfully .
I am editing this and giving you sql table complete details
DROP TABLE IF EXISTS `member`;
CREATE TABLE IF NOT EXISTS `member` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rand` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
`course` text NOT NULL,
`gender` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(255) NOT NULL,
`zip` varchar(255) NOT NULL,
`comment` text NOT NULL,
`Aboutme` text NOT NULL,
`dat` varchar(255) NOT NULL,
`tim` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `member` (`id`, `rand`, `email`, `name`, `lname`, `phone`, `dob`, `course`, `gender`, `address`, `city`, `state`, `zip`, `comment`, `Aboutme`, `dat`, `tim`) VALUES
(1, 'jrf20180961828', 'kk122344545#hotmail.com', 'Kishan', 'Yadav', '9717111111', '2018-09-01', 'paper first,Political Science,Philosophy,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'Good person.', '', '06-09-2018', '11:24:16pm'),
(2, 'jrf20180914721', 'kk1#gmail.com', 'Rohan', 'Yadav', '9717111111', '2018-09-01', 'paper first,Philosophy,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'Good Person.', '', '06-09-2018', '11:25:44pm'),
(5, 'jrf20180958284', 'ykishan94612121#gmail.com', 'kiran', 'Singh', '9717111111', '2018-07-07', 'paper first,Political Science,History,', 'female', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'nnbmnm', '', '10-09-2018', '10:11:34pm'),
(4, 'jrf20180932851', 'kk12#gmail.com', 'Pankaj', 'Yadav', '9717111111', '2018-09-01', 'paper first,Philosophy,Psychology,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'nmbmbn', '', '10-09-2018', '10:10:19pm'),
(6, 'jrf20180929250', 'hjh#gmail.com', 'John', 'Corter', '9717111111', '2018-09-06', 'paper first,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'sxs', '', '11-09-2018', '12:09:49am');
COMMIT;
And second table is
DROP TABLE IF EXISTS `assignment`;
CREATE TABLE IF NOT EXISTS `assignment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rand` varchar(255) NOT NULL,
`course` varchar(255) NOT NULL,
`quest_id` varchar(255) NOT NULL,
`time` varchar(255) NOT NULL,
`date` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `assignment` (`id`, `rand`, `course`, `quest_id`, `time`, `date`) VALUES
(1, 'jrf20180914721', 'paper first', '2', '10:05:48pm', '2018-09-10'),
(2, 'jrf20180961828', 'paper first', '2', '10:06:49pm', '10-09-2018'),
(3, 'jrf20180914721', 'History', '2', '10:08:03pm', '10-09-2018'),
(4, 'jrf20180958284', 'History', '2', '10:12:05pm', '10-09-2018'),
(5, 'jrf20180914721', 'paper first', '1', '10:19:23pm', '10-09-2018'),
(6, 'jrf20180932851', 'History', '3', '12:07:48am', '11-09-2018');
COMMIT;
And my output should be kind of this, I join two table to get this output.
Attached pic of my output
I get this output using above query. Sorry for my english.
After chat in db-fiddle:
select distinct t.id, t.rand, name, lname, email, phone, if(quest_id='2','2',NULL) as quest-id
from `member` t
left join assignment a on t.rand= a.rand
where t.course like '%History%'
and (a.course like '%History%') or a.id is null
Member constrained to course, assignment same course, quest(ion)_id 2 displayed if it was found, otherwise leave the field as NULL.
You can use transaction to separate Query execution
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();

Make new users automatically follow a user

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"))";
}

Wrong Value showing in echo after request

I am trying to make a team name shown from a URL pulling information from my database regarding that team
<?
$query = "select * from teams where
name='".$mysqli->real_escape_string($_REQUEST['name'])."'";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$id = $row['id'];
$name = $row['name'];
$lon = $row['lon'];
$lat = $row['lat'];
$distance = $row['distance'];
$postcode = $row['postcode'];
$phone = $row['phone'];
?>
This worked fine until I put a second team name in the database and now all pages shows that name
the URL is http://domain.com/team.php?name=Test%20TeamA
and its showing Test TeamB and not the required one above
I have checked this on 2 pc's just to make sure its not something wrong with my form i used to put the data into my database or any values hanging about in my browser
why is this doing it?
SQL DUMP
--
-- Table structure for table `teams`
--
CREATE TABLE IF NOT EXISTS `teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`lat` varchar(32) NOT NULL,
`lon` varchar(32) NOT NULL,
`distance` varchar(20) NOT NULL,
`postcode` varchar(20) NOT NULL,
`phone` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `teams`
--
INSERT INTO `teams` (`id`, `name`, `lat`, `lon`, `distance`, `postcode`, `phone`) VALUES
(1, 'Test TeamA', '52.483038', '0.178962', '12.9', 'PE15 0JJ', ''),
(3, 'Test TeamB', '52.45645', '0.823423', '12', '', '01231223');
This is not the idea answer for a question like this but please see all the replies under my question
In my case it was a error on another page that i was including on my page
My best advice is to do what NickCoon had commented
echo $query;
to see the query that is being used. then strip all your page down to eliminate the issue

Count function()

I have these two table with some data sample in them. I would like to to pull out number of classifieds in each category. I gave it a try, and I got (2) in each one which is not correct. So hopefully someone will help me with this.
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`name` text COLLATE utf8_unicode_ci NOT NULL,
`subcategory_id` int(2) NOT NULL DEFAULT '0',
`parent_id` int(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=27 ;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `name`, `subcategory_id`, `parent_id`) VALUES
(1, 'Announcements', 0, 0),
(2, 'Employment', 0, 0),
(3, 'Items For Sale', 0, 0),
(4, 'Services', 0, 0),
(5, 'Garage Sales', 0, 0),
(6, 'Automobiles', 0, 0),
(7, 'Announcement1', 1, 1),
(8, 'Announcement2', 1, 1),
--
-- Table structure for table `classifieds`
--
CREATE TABLE IF NOT EXISTS `classifieds` (
`classified_id` int(255) NOT NULL AUTO_INCREMENT,
`title` text COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`category_id` int(10) NOT NULL,
`name` text COLLATE utf8_unicode_ci NOT NULL,
`authorized` int(10) NOT NULL DEFAULT '0',
PRIMARY KEY (`adid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=177 ;
--
-- Dumping data for table `classifieds`
--
INSERT INTO `classifieds` (`classified_id`, `title`, `description`, `category_id`, `name`, `authorized`) VALUES
(1, 'Test Classified', 'Here is the First Test classified listing.', 1, 1);
INSERT INTO `classifieds` (`classified_id`, `title`, `description`, `category_id`, `name`, `authorized`) VALUES
(2, 'GMC For Sell', 'Looks like new 1979 GMC.', 6, 1);
here
$query = "SELECT category_id, COUNT(title) FROM classifieds GROUP BY category_id";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result)
$num_items_in_category = $row['COUNT(title)'];
echo "<><a href='category-".$row['id'].".php' >".$row['name'].$num_items_in_category."</a></li>";
Thanks
Change the SQL a bit, and loop through the results?
$query = "SELECT c.id, c.name,
COUNT(cl.category_id) AS num_items_in_category
FROM category_id c
LEFT JOIN aclassifieds cl ON cl.category_id=c.id
GROUP BY c.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "<li><a href='category-".$row['id'].".php' >".$row['name'].$row['num_items_in_category']."</."</a></li>";
}
Just in case someone else wants to benefit my this:
enter $query = "SELECT c.id, c.name,
COUNT(cl.title) AS num_items_in_category
FROM categories c
LEFT JOIN classifieds cl ON cl.category_id=c.id
GROUP BY c.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "".$row['name'].$row['num_items_in_category']."";
}
here
Thanks

Categories