users and posts database issue - php

Is it true that after a user signs up, a sql table is create for him to store his posts ?
I make it similar in mysql after the man insert him into my page. The database is the same name with but the table name is made when he log in first time.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
public function Users($username)
{
$table_name=$username."_tb";
echo $table_name."<br/>";
mysql_connect(localhost,$username, $password) or die("unable to connect to database ".mysql_error());
echo $database."<br/>";
mysql_selectdb($database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL)";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
But it display only table_name and an error, the database name not display. Error is NO DATABASE IS SELECTED/
EDIT
This class is call after he sign up
I also have a function postApost but when I do
ob_start();
session_start();
require("Users_DB.php");
$name=$_SESSION['user'];
echo 'Welcome '.$name;
$username=new UserDB($name);
there is no table created

Two variables with same name $username. Use $this for accessing variable of class. Missing quote(") with localhost - it must be string type parameter. and this code can't create table on Database because you use AUTO_INCREMENT on your code but forgot to mention that as a PRIMARY KEY. I think the following code help you a lot.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
function __construct($user_name)
{
$this->table_name=$user_name."_tb";
echo $this->table_name."<br/>";
mysql_connect("localhost",$this->username, $this->password) or die("unable to connect to database ".mysql_error());
echo $this->database."<br/>";
mysql_selectdb($this->database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$this->table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL, PRIMARY KEY (id))";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
And you can use this class by the following way :
$clsName = new Users('username');

Create one table:
CREATE TABLE Posts (
id TINYINT(4) NOT NULL AUTO_INCREMENT,
user VARCHAR(20) NOT NULL,
title VARCHAR(128) NOT NULL,
date_post DATETIME,
date_edit DATETIME,
post_content TEXT NOT NULL
)
Inserting new posts:
$insert = "
INSERT INTO Posts (
user,
title,
date_post,
date_edit,
post_content
) VALUES (
'$username',
'$title',
NOW(),
NOW(),
'$post_content'
)
";
Updating is simple:
$update = "
UPDATE Posts SET
title = '$title',
post_content = '$post_content',
date_edit = NOW()
WHERE id = '$postid';
";
Get all posts for user:
$posts = "
SELECT title, date_post, date_edit, post_content
FROM Posts
WHERE user = '$username'
ORDER BY date_post
";

Related

Create TABLE using PHP, according to input [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 3 years ago.
I am about to create a table, but I want to declare it based on the user's input. thankyou for any response, all answers are appreciated, more power!
I am receiving this error (Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''2020-2021' ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR' at line 1)
here's the sample code I am doing.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mias";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$table = $_POST['usersinput'];
// sql to create table
$sql = "CREATE TABLE $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Try this code by replacing your code. It will work. i have tried. Problem in your last line of your code.
CREATE TABLE $table(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30),
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
As Nigel has said in the comment, it's definitely a bad idea to allow user input to create a table.
How I would think about doing this would be to use relationships between the Table Guests and the Table or Booking you want them to be added to.
You would just need to create two tables, one for the Booking and one for the Guests then in the Guests table, have a Booking_ID field which would contain the ID of the bookings the user should be added to.
This way, when you want to look for Guests for a specific table, you would be able to do SELECT * FROM MyGuests WHERE booking_id=[the booking id] and this would return the guests for that table.
Like other users stated there are several reasons (most importantly security) not to do that, but if you really want it you have to use concatenation for your string:
Option
$sql = "CREATE TABLE {$table}(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
Option
$sql = "CREATE TABLE" . $table . "(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";

I can't update table's columns in MySQL database

I have created a tabe with values using this command :
CREATE TABLE `news` (
`id` int(11) NOT NULL auto_increment,
`title` text NOT NULL,
`content` text NOT NULL,
`price` text NOT NULL,
`link` text NOT NULL,
`ppcode` text NOT NULL,
`type` text NOT NULL,
PRIMARY KEY (`id`)
)
And when i use this php codes i cant update any value of the columns :
if (isset($_POST['edit'])){
$delsql = "UPDATE news SET title='$newsubject',content='$newdisc',link='$newlink',
price='$newprice',ppcode='$newppcode' WHERE id = '$id'";
$result = mysql_query($delsql) or die(mysql_error());
echo 'OK';
}
Note : the version of MySQL is 3.5.2.2 and the version of PHP is 5.3
Use mysqli_* functions or PDO!!!!
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
$stmt = $conn->prepare("UPDATE news SET title=?,content=?,link=?,price=?,ppcode=? WHERE id =?");
$stmt->bind_param('sssdii',$newsubject,$newdisc,$newlink,$newprice,$newppcode,$id);
// i corresponding variable has type integer
// d corresponding variable has type double
// s corresponding variable has type string
// b corresponding variable is a blob and will be sent in packets
$stmt->execute();
$row_count= $stmt->affected_rows;
$stmt->close();
$conn->close();
Beside all the suggestion on the comments
You have
WHERE id = '$id'";
but id is integer not text
CREATE TABLE `news` (
`id` int(11) NOT NULL auto_increment,
In image of phpmyadmin that you provided in comments you can see that A_I (auto_increment) is not active. Also primary key is not set. Set A_I to true for id and set it as primary key (under Index) in phpmyadmin. Then test it with your code.
Of course first insert new data which will have auto incremented id's.

Create 2nd tables and add data

I have this task from school, and I am confuse and lost on how I got to do this.
So basically I have to create 2 tables to the database but I have to created from php.
I have created the first table, but not the second one for some reason.
And then, I have to populate first and second tables with 10 and 20 sample records respectively, populate, does it mean like adding more fake users? if so is it like the code shown below?
*I got error on the populating second part as well
Thank you so much for the help.
<?php
$host = "host";
$user = "me";
$pswd = "password";
$dbnm = "db";
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
if (!$conn)
die ("<p>Couldn't connect to the server!<p>");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("<p>Database Not Selected</p>");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL,
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
The others have addressed one of your issues, so this is in relation to not being able to add values to your tables (populate). Your connection link is $conn -
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
ie.
$query_result1 = #mysqli_query($conn, $sql);
but when you are adding your values to the tables, you changed your connection link to $dbConnect
...
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
...
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
To insert multiple values into your table you could add a comma and additional parentheses ,() -
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2),(2,3),(3,1)";
$queryResult13=#mysqli_query($conn,$sqlSt13);
Or you could use mysqli_multi_query, and list each one-
//populating 2nd table
$sqlSt13 ="INSERT INTO myfriends VALUES (1,2);";
$sqlSt13 .="INSERT INTO myfriends VALUES (2,3);";
$sqlSt13 .="INSERT INTO myfriends VALUES (3,1);";
$queryResult13=#mysqli_query($conn,$sqlSt13);
see the manual for mysqli_multi_query - php.net/manual/en/mysqli.multi-query.php
You have an extra comma here that might cause an error:
friend_id2 INT NOT NULL,
should be:
$sqlMyfriends = "CREATE TABLE `myfriends` (
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
I wish I could be at school now :)
You have the following errors in code:
1) $queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
Is correct: $queryResult3 = #mysqli_query($dbConnect,$sqlSt3);
2) $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL,
)";
Is correct: $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL)";
3) $queryResult3 = #mysqli_query($conn,$sqlSt3);
Is correct: $queryResult3 = mysqli_query($conn,$sqlSt3);
Code correct is:
Couldn't connect to the server!");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("Database Not Selected");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = mysqli_query($conn,$sqlSt3);
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
I hope to help !

SQL query retrieve fields from current date

This is my database SQL code;
CREATE TABLE ProductType
(
ptID int not null auto_increment,
pType varchar(30),
PRIMARY KEY(ptID)
)ENGINE=InnoDB;
CREATE TABLE Service
(
sID int not null auto_increment,
description varchar(30) not null,
revenue int,
stID int not null,
PRIMARY KEY(sID),
FOREIGN KEY(stID) references ServiceType(stID)
)ENGINE=InnoDB;
CREATE TABLE Product
(
pID int not null auto_increment,
model varchar(30) not null,
cogs int,
ptID int not null,
PRIMARY KEY(pID),
FOREIGN KEY(ptID) references ProductType(ptID)
)ENGINE=InnoDB;
CREATE TABLE Sale
(
saleID int not null auto_increment,
assetID int not null,
eID int not null,
sID int not null,
pID int,
saDate date not null,
PRIMARY KEY(saleID),
FOREIGN KEY(eID) references Employee(eID),
FOREIGN KEY(sID) references Service(sID),
FOREIGN KEY(pID) references Product(pID)
)ENGINE=InnoDB;
CREATE TABLE Employee
(
eID int not null auto_increment,
firstName varchar(30) not null,
lastName varchar(30) not null,
phone varchar(30),
email varchar(30),
PRIMARY KEY(eID)
)
This is my attempt but I don't know how to access the 'revenue' field from 'Service' when I am querying the 'Sale' table.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("pnl") or die(mysql_error());
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM Sale WHERE saDate = CURDATE()")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "revenue: ".$row['revenue'];
?>
Can anyone give me an example of how I would write a php script to retrieve the revenue of all sales for the current date?
Also this was my first attempt at SQL and relational database models, so if you notice any critical mistakes I've made or things I can improve please let me know!
Try this way. Name the SUM field and access it by given name:
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT SUM(Service.revenue) sum FROM Service JOIN Sale ON Sale.sID = Service.sID WHERE Sale.saDate = $some_date") or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "revenue: ".$row['sum'];
If sID on sales and Service both are same and unique to every sales then you can use query like this:
$result = mysql_query(SELECT Sale.saleID, Sale.assetID, Sale.eID, Sale.sID, Sale.pID, Sale.saDate, Service.revenue "."FROM Sale, Service "."WHERE Sale.sID = Service.sID AND Sale.saDate = CURDATE()) or die(mysql_error());
Or if Service.sID = Sale.saleID then change acordingly.
This way you can control which column exactly you would like to retrive from each table.

update a rss feed in database

I'm reading and store a RSS feed in my database.I'm using this code
<?php
include_once 'db.php';
$homepage = file_get_contents('http://rss.cnn.com/rss/edition_us.rss');
$movies = new SimpleXMLElement($homepage);
foreach($movies->channel->item as $opt){
$title= $opt->title;
$tittle=mysql_real_escape_string($title);
$link=$opt->link;
$links=mysql_real_escape_string($link);
$des=$opt->description;
$dess=mysql_real_escape_string($des);
$sql="INSERT INTO store_feed (title, link, description)
VALUES ('$tittle','$links','$dess')";
$result=mysql_query($sql) or die('Error, insert query failed');
}
?>
and table structure is
Table structure for table store_feed
CREATE TABLE IF NOT EXISTS `store_feed` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(200) NOT NULL,
`link` varchar(200) NOT NULL,
`description` varchar(500) NOT NULL,
`feedburner` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
now my requirement is when insert a new record if link is same then update only title and description of this field without insert record again.
in other word I want to stop duplicate data if link is same.
Usually, I do something like this:
WARNING: UNTESTED CODE!
$sql = "SELECT id FROM store_feed WHERE link = '$links' LIMIT 1";
$rs = mysql_query($sql) or die( mysql_error() );
if( mysql_num_rows($rs) > 0)//we got link
{
$r = mysql_fetch_array($rs);
$id = $r['id'];
$sql = "UPDATE store_feed SET title = '$title', description = '$dess' WHERE id = '$id'";
mysql_query($sql) or die( mysql_error() );
} else {
$sql = "INSERT INTO store_feed (title, link, description) VALUES ('$tittle','$links','$dess')";
mysql_query($sql) or die( mysql_error() );
}
Before you inserting every feed into database just check title and description exist in database if not exist insert that row into database.
http://www.exceptionhandle.com

Categories