Inserting data from form to mysql database - php

I am using PHP to send data from a form to mysql database, when I use this code:
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
phone VARCHAR(60) NOT NULL,
password VARCHAR(60) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
email VARCHAR(50),
pelak VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci,
reg_date TIMESTAMP
)";
it works perfectly, but when I use:
$field_table = $_POST['phone'];
$sql = "CREATE TABLE '{$field_table}' (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
phone VARCHAR(60) NOT NULL,
password VARCHAR(60) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
email VARCHAR(50),
pelak VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci,
reg_date TIMESTAMP
)";
it create table in phpmyadmin but gives an error:
"#1146 - Table 'username.table_name' doesn't exist"

Related

php Mysql CREATE TABLE If does't exist only once

I only want to create the table once if it doesn't exist. Will this code create a new table every time? If yes, how do I prevent it?
$queryCreateUsersTable = "CREATE TABLE IF NOT EXISTS EmailList (
`ListName` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`FirstName` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`Email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`ID` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`IP` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`ConfirmedEmail` tinyint(1) DEFAULT NULL,
`Subscribed` tinyint(1) DEFAULT 0,
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
if(!$conn->query($queryCreateUsersTable))
{
echo "Table creation failed: (" . $dbConnection->errno . ") " . $dbConnection->error;
}
CREATE TABLE IF NOT EXISTS means it will only create the table if it is not present.
Exactly as what CREATE TABLE IF NOT EXISTS means. Create a table if table does not exist.
Therefore, no it does not.

Set names and collation UTF8 does not works in SimpleXML or MySQL

I am gettin XML data which header has utf8 setted:
<?xml version="1.0" encoding="utf-8"?>
I download it using CURL and it is downloaded correctly with UTF8 chars.
I parse that downloaded xml files using SimpleXML using this code:
<?php
class XMLParser{
public function __construct(){
}
public function parseFile($path){
$xml = '';
if(!is_null($path)){
$file = file_get_contents($path);
if(!is_null($file)){
$xml = new SimpleXMLElement($file);
}
else{
echo 'there is no file';
}
}
else{
echo 'Wrong path!';
}
return $xml;
}
}
?>
And send it to database calling PDO and stored procedures, connect script has defined utf8:
$this->PDO->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
Each table has utf8_general_ci
But in table are chars like this:
León de Huánuco - Cienciano
UPDATE!
CREATE TABLE code:
CREATE TABLE IF NOT EXISTS `jcjdkdtaur`.`fixtures` (
`Id` INT(32) NOT NULL,
`UpdatedDate` varchar(100) DEFAULT NULL,
`DateTime` datetime NULL DEFAULT NULL,
`Date` date NULL DEFAULT NULL,
`Time` time NULL DEFAULT NULL,
`Status` VARCHAR(40) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL DEFAULT NULL,
`League` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL DEFAULT NULL,
`LeagueID` INT(11) DEFAULT NULL,
`SportID` tinyint DEFAULT 1,
`SportName` varchar(30) DEFAULT 'football',
`Cup` varchar(20) DEFAULT NULL,
`Country` VARCHAR(60) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL DEFAULT NULL,
`EventName` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL DEFAULT NULL,
`HomeTeam` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL DEFAULT NULL,
`HomeTeam_Id` INT(11) NULL DEFAULT NULL,
`AwayTeam` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL DEFAULT NULL,
`AwayTeam_Id` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`Id`,`HomeTeam_Id`,`AwayTeam_Id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
INSERT STORE PROCEDURE I CALL IT FROM PHP:
DROP PROCEDURE IF EXISTS insupd_Fixtures;
DELIMITER //
CREATE PROCEDURE insupd_Fixtures(IN p_id int(32), IN p_updated varchar(100), IN p_datetime datetime, IN p_date date,
IN p_time time, IN p_status varchar(40),IN p_league varchar(255),IN p_leagueid int(11), IN p_sportid tinyint, IN p_sportname varchar(30),
IN p_cup VARCHAR(20), IN p_country VARCHAR(60),IN p_eventname varchar(255),IN p_hometeam varchar(255),IN p_hometeam_id int(11),
IN p_awayteam varchar(255),IN p_awayteam_id int(11)
)
BEGIN
INSERT INTO fixtures(`Id`,`UpdatedDate`,`DateTime`,`Date`,`Time`,`Status`,`League`,`LeagueID`,`SportID`,`SportName`,`Cup`,`Country`,`EventName`,
`HomeTeam`,`HomeTeam_Id`,`AwayTeam`,`AwayTeam_Id`)
VALUES
(p_id,p_updated, p_datetime, p_date, p_time, p_status,p_league, p_leagueid, p_sportid, p_sportname, p_cup,p_country,
p_eventname,p_hometeam,p_hometeam_id,p_awayteam,p_awayteam_id)
ON DUPLICATE KEY UPDATE
Id=p_id,
UpdatedDate = p_updated,
DateTime=p_datetime,
Date=p_date,
Time=p_time,
Status=p_status,
League=p_league,
LeagueID = p_leagueid,
SportID = p_sportid,
SportName = p_sportname,
Cup=p_cup,
Country=p_country,
EventName=p_eventname,
HomeTeam=p_hometeam,
HomeTeam_Id=p_hometeam_id,
AwayTeam=p_awayteam,
AwayTeam_Id=p_awayteam_id;
END //

Result consisted of more than one row SQL=INSERT INTO

While inserting first time it gives following error: "Result consisted of more than one row". When i try to insert record second time it gives error with message duplicate entry.
SQL=INSERT INTO `master_user` (`name`,`user_name`,`email`,`password`,`system_name_of_friend`,`system_no_of_friend`,`registered_from_site`,`registered_on`,`is_existing_user`) VALUES ('FirstName LastName','username','demo#mail.com','8c71eede42e38709e9e836021b0b9b9b','','','site','','1')
any one help will be appropriated and following is the table structure which will be get help to tracking this issue very easily and get the solution for this.
CREATE TABLE IF NOT EXISTS `master_user` (
`master_user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`user_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`system_name_of_friend` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`system_no_of_friend` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`registered_from_ip` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
`registered_from_site` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
`registered_on` datetime DEFAULT NULL,
`is_existing_user` bit(1) NOT NULL DEFAULT b'0',
PRIMARY KEY (`master_user_id`),
UNIQUE KEY `ukMasterUser_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1293 ;
I have changed the few words from column Which are conflicting and resolved.

mysql php Cannot take foreign key value

Hello I have a problem with my php code.. there are 3 tables for a recruitment system.
CREATE TABLE IF NOT EXISTS `members` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(25) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varchar(25) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`cpassword` varchar(25) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`email` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`role` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`uid`)'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=60 ;
The candidate table :
CREATE TABLE IF NOT EXISTS `candidate` (
`fullname` varchar(35) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`webpage` varchar(150) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`tel` int(35) NOT NULL,
`nationality` varchar(35) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`position` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`interviewed` varchar(30) NOT NULL DEFAULT 'No',
`rating` varchar(30) NOT NULL,
`c_id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL,
PRIMARY KEY (`c_id`),
KEY `uid` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=135 ;
The academic table :
CREATE TABLE IF NOT EXISTS `academic_candidate` (
`degree` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`exp_years` varchar(25) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`comment1` varchar(300) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`proposed_positions` varchar(25) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`research_years` varchar(25) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`comment2` varchar(300) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`department` varchar(25) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`a_id` int(25) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL,
`c_id` int(11) NOT NULL,
PRIMARY KEY (`a_id`),
UNIQUE KEY `id` (`a_id`),
KEY `uid` (`uid`),
KEY `c_d` (`c_id`),
KEY `c_id` (`c_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=40 ;`
-- Constraints for table academic_candidate
ALTER TABLEacademic_candidate
ADD CONSTRAINTacademic_candidate_ibfk_1FOREIGN KEY (uid) REFERENCESmembers(uid) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINTacademic_candidate_ibfk_2FOREIGN KEY (c_id) REFERENCEScandidate(c_id) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table candidate
ALTER TABLEcandidate
ADD CONSTRAINTcandidate_ibfk_1FOREIGN KEY (uid) REFERENCESmembers(uid) ON DELETE CASCADE ON UPDATE CASCADE;
--
Now, I use this query in order to store the values in the table academic_candidate
session_start();
$query = "SELECT * FROM academic_candidate WHERE degree = '$degree'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count > 0){
echo "You ALready complete the form </br>";
header("Location:../candidate/candidate_index.php");
}
else{
$degree =($_POST['degree']);
$exp_years = ($_POST['exp_years']);
$comment1 = ($_POST['comment1']);
$proposed_positions = ($_POST['proposed_positions']);
$research_years=($_POST['research_years']);
$comment2=($_POST['comment2']);
$department=($_POST['department']);
$uid=($_SESSION['uid']);
$query1 = "INSERT INTO academic_candidate
(degree,exp_years,comment1,proposed_positions,research_years,comment2,department,uid,c_id)
SELECT
'$degree','$exp_years','$comment1','$proposed_positions','$research_years','$comment2','$department','$uid','$c_id'
FROM candidate
WHERE uid='$uid' AND c_id='$c_id' ";
$result = mysql_query($query1);
if(!$result){
echo "Error";
die (mysql_error());
}
else{
header("Location:../candidate/view_application.php");
}
}
My problem is that stores all the values on the table academic_candidate table but the c_id is 0 . What can I do in order to take the candidate.c_id?
You're passing literal values to your INSERT INTO statement.
Consider the difference:
SELECT 'bar' FROM foo;
SELECT bar FROM foo;
Here's a demo on SQLFiddle.
Looking at your query:
SELECT '$degree'
Is not the same as:
SELECT degree
One of these is simply echoing whatever value you pass in, the other is actually selecting a column from the DB.

Find posts of user grouped by month, unixtime

I'd like to find the number of posts for each user grouped by month.
I'm currently using INT(10) unsigned to store the date of posts.
what would be a super fast way to do this?
CREATE TABLE IF NOT EXISTS `media` (
`pid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`class` tinyint(1) NOT NULL DEFAULT '1',
`date_class_changed` int(10) unsigned NOT NULL,
`title` char(5) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`url` varchar(1024) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`media` enum('image','video') CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`thumb` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`description` varchar(140) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(16) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`date` int(10) unsigned NOT NULL,
`file` varchar(1024) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`hash` char(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`hashtag` text CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`meta` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`ip` int(10) unsigned NOT NULL,
`kind` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`pid`),
UNIQUE KEY `title` (`title`),
KEY `hash` (`hash`),
KEY `class_date` (`class`,`date_class_changed`),
KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1022724 ;
This is the table, I'm talking about, I'd like to display the number of posts for each user for each mont, such as: september 2012, User X, N posts etc..
The query I'm using after the help from #fthiella is:
SELECT
DATE_FORMAT(FROM_UNIXTIME(`date`), '%Y-%m') as YearMonth, username, COUNT(*) as Posts
FROM
media
WHERE username = 'foobar'
GROUP BY 1
ORDER BY 1 DESC
thanks God it's fast enough, now I'll try to optimize in case it's not using an index, but for now with almost 1M record is doing good. cheers.
SELECT
DATE_FORMAT(FROM_UNIXTIME(`date`), '%Y-%m') as YearMonth,
username,
COUNT(*) as Posts
FROM
media
GROUP BY
DATE_FORMAT(FROM_UNIXTIME(`date`), '%Y-%m') as YearMonth,
username

Categories