Create new SQL table on form submit IF TABLE NOT EXIST - php

I am new to php and SQL so this is probably an easy question but I could not find any good sources online.
I am trying to create a SQL table when someone submits a form and this is what I have so far
include("dbstufflive.php");
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die("Couldn't connect to server");
$sql = "CREATE TABLE IF NOT EXISTS `$company` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(80) NOT NULL,
`contact` varchar(50) NOT NULL,
`email` varchar(80) NOT NULL,
`phone` varchar(13) NOT NULL,
... (long list of table data)
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ";
mysqli_query($cxn,$sql);
I will of course be doing other stuff with this table but I think I have most of that under control.
The problem is that this statement does not actually create my table :( The SQL statement works in phpadmin when I enter it as is and also there are no errors when the script runs. So it goes through all of this, and more, and seems to work but the table simply doesn't appear.
I can supply more code if needed but I don't want to paste more code here than is necessary.
Thanks in advance for any help from the community.
EDIT:
I was using wrong DBinfo...wow, I am not very bright.

Your SQL Statement looks fine - from the looks of it, you are missing your login credentials. An efficient way to do so:
// Add this line
require_once('config.php');
// Then change the variables below to pull your credentials from that file.
$cxn = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD)
or die("Couldn't connect to server");
$sql = "CREATE TABLE IF NOT EXISTS `$company` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(80) NOT NULL,
`contact` varchar(50) NOT NULL,
`email` varchar(80) NOT NULL,
`phone` varchar(13) NOT NULL,
... (long list of table data)
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ";
mysqli_query($cxn,$sql);
Then create a new file called config.php in same directory. Put your credentials:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASSWORD', 'your_password');
define('DB_DATABASE', 'database_name');
?>

You should check the result of mysqli_query (as far as i know it returns false on failure). See mysqli documentation for details, where you can read, that "Create table doesn't return a resultset" but True/false on sucess/failure.
example:
if (!mysqli->query($cxn,$sql)) {
printf("Error: %s\n", mysqli_error($cxn));
}

Related

Getting sql error PHP

I am following a codeiniter tutorial, which tells me to make a database with the following code (using mysql):
$sql = "create database login;
CREATE TABLE IF NOT EXISTS `user_login` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ";
I try to run this, using my own php code, but i keep getting this error, and have no idea how to solve it:
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 'CREATE TABLE IF NOT EXISTS `user_login` ( `id` int(11) NOT NULL AUTO_INCREM' at line 2
No idea what it could be.
create database login;
and
CREATE TABLE IF NOT EXISTS `user_login` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
are two commands which are to be executed separately. Have the database created before you try to create the table - either via a SQL client or by executing something like:
$sql1 = 'create database login;';
$sql1->execute();
$sql2 = 'CREATE TABLE IF NOT EXISTS `user_login`...';
$sql2->execute();

PHP SQL query slow?

Here is my function which i am using to un-follow users.It first DELETE the relationship between users and all the notifications that are related to this relationship.Then it INSERT a new notification for user which we are going to un-follow and then UPDATE his followers count (as one follower has left).I am using multi_query and this query seems to be bit slower on large database and i want to know whether it's a good practice or not or is there is any more complex form of query to get the job done.
PHP Function
// 'By' is the array that hold logged user and 'followed' is the user id which we are going to unfollow
function unFollowUser($followed,$by) {
$following = $this->getUserByID($followed);// Return fetch_assoc of user row
if(!empty($following['idu'])) { // if user exists
// return user followers as number of rows
$followers = $this->db->real_escape_string($this->numberFollowers($following['idu'])) - 1;
$followed_esc = $this->db->real_escape_string($following['idu']);
$by_user_esc = $this->db->real_escape_string($by['idu']);
// delete relationship
$query = "DELETE FROM `relationships` WHERE `relationships`.`user2` = '$followed_esc' AND `relationships`.`user1` = '$by_user_esc' ;" ;
// delete notification (user started following you )
$query.= "DELETE FROM `notifications` WHERE `notifications`.`not_from` = '$by_user_esc' AND `notifications`.`not_to` = '$followed_esc' ;" ;
// Insert a new notification( user has unfollowed you)
$query.= "INSERT INTO `notifications`(`id`, `not_from`, `not_to`, `not_content_id`,`not_content`,`not_type`,`not_read`, `not_time`) VALUES (NULL, '$by_user_esc', '$followed_esc', '0','0','5','0', CURRENT_TIMESTAMP) ;" ;
// update user followers (-1)
$query .= "UPDATE `users` SET `followers` = '$followers' WHERE `users`.`idu` = '$followed_esc' ;" ;
if($this->db->multi_query($query) === TRUE) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
Table structures
--
-- Table structure for table `notifications`
--
CREATE TABLE IF NOT EXISTS `notifications` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`not_from` int(11) NOT NULL,
`not_to` int(11) NOT NULL,
`not_content_id` int(11) NOT NULL,
`not_content` int(11) NOT NULL,
`not_type` int(11) NOT NULL,
`not_read` int(11) NOT NULL,
`not_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Table structure for table `relationships`
--
CREATE TABLE IF NOT EXISTS `relationships` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user1` int(11) NOT NULL,
`user2` int(11) NOT NULL,
`status` int(11) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`idu` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`password` varchar(256) NOT NULL,
`email` varchar(256) NOT NULL,
`first_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`verified` int(11) NOT NULL,
`posts` text CHARACTER SET utf32 NOT NULL,
`photos` text CHARACTER SET utf32 NOT NULL,
`followers` text CHARACTER SET utf32 NOT NULL,
UNIQUE KEY `id` (`idu`),
UNIQUE KEY `idu` (`idu`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
In my testing, multi_query has been the fastest way to execute multiple different queries. Why do you feel it's running slow? Compared to what?
Anyway, improvements could come from adding indexes to some of the columns you search frequently:
relationships.users2
relationships.users1
notifications.not_from
notifications.not_to
users.idu
Adding indexes makes searching faster, but it has at least two downsides:
Makes the DB a lot more resource hungry, which could affect your server performance
Makes writing operations take longer
I don't see any problem with your current queries. Really consider whether the slow performance you're seeing comes from the DB queries themselves, or from the rest of your PHP process. Try measuring the script time with the queries, then skipping the queries and taking another measurement (you could hardcode query results). It will give you an idea of whether the slowness is attributable to something else.
Either way, benchmark.
Try creating index on user where deletes are running , this may speed up query

Valid MySQL Delete Query returning non-object

This one's a mystery to me and no one that I've read up on so far has had this issue, and I'm losing my mind here, so here goes. I'm trying to run this simple query from php on a mysql database with a user that has all required privileges (usually there is more than one entry in the ID array):
$sqlDelete = 'DELETE FROM wsa.customers WHERE `id` IN (18)';
$result = $conn->query($sqlDelete);
When I run this code from phpmyadmin and workbench this executes just fine, but not using php on the server (though it does handle updates and inserts without issue).
The $result is not a result object (though it should be) and I see no error or warnings at all...everything is as if nothing went badly though the user is obviously not deleted.
I'd just like to get input on where I should be looking as this is not a syntax issue....I've run out of ideas.
Thanks
UPDATE ON SCHEMA QUESTION:
CREATE TABLE `agreements` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`creator_id` int(11) NOT NULL,
`term` tinyint(4) NOT NULL,
`contractDate` date NOT NULL,
PRIMARY KEY (`id`),
KEY `creatorid_idx` (`creator_id`),
CONSTRAINT `userid` FOREIGN KEY (`creator_id`) REFERENCES `master`.`login` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
CREATE TABLE `customers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`agreement_id` int(11) NOT NULL,
`name` varchar(128) NOT NULL,
`plan` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `agreementid_idx` (`agreement_id`),
CONSTRAINT `agr_id` FOREIGN KEY (`agreement_id`) REFERENCES `agreements` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;
UPDATE 2: Connnection Details:
$dbhost = 'localhost';
$dbuser = 'xxx';
$dbpass = 'yyy';
$conn;
$conn = new mysqli($dbhost, $dbuser, $dbpass, 'wsa');
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
Sorry folks...in the end I was erroneously using if(!result) to test whether the query went through on a previous insert query to the one shown and it was causing the whole transaction to fail. My apologies. Thanks to #Darwin von Corax for pointing me in the right direction.

Mysqli not finding row

i am trying to let a user login here is my login script atm im just checking if the username exists but for some reason its not finding any records even though the user name is right
<?php if(isset($_POST)){
print_r($_POST);
//Variables from the table
$usernamelogin = $_POST['usernamelogin'];
$passwordlogin = $_POST['passwordlogin'];
//Prevent MySQL Injections
$usernamelogin = stripslashes($usernamelogin);
$passwordlogin = stripslashes($passwordlogin);
$usernamelogin = mysqli_real_escape_string($con, $usernamelogin);
$passwordlogin = mysqli_real_escape_string($con, $passwordlogin);
$loginquery = mysqli_query($con,"SELECT * FROM reg_users WHERE user ='$usernamelogin' AND authorised ='1'") or die("Can not query DB.");
$logincount = mysqli_num_rows($loginquery);
if($logincount == 1){
echo "user exists";
} else {
echo "User doesnt exist";
}
}
?>
my table is called reg_users and user is the column the username goes into. i am doing the same thing on register and that works
Any ideas guys?
table is
`reg_users` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`firstname` varchar(30) DEFAULT NULL,
`surname` varchar(30) DEFAULT NULL,
`user` varchar(255) DEFAULT NULL,
`password` varchar(512) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`banned` int(1) DEFAULT '0',
`authorised` int(1) DEFAULT '0',
`activationcode` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1;
And the sqlfiddle is here
Here is the config.php which is called in the header of the page
<?php //Information to connect to your MySQL Server AND DB
$hostdb = "localhost";
$userdb = "test_nathan";
$passworddb = "xxxxx";
$db = "test_nathan";
//Connect to MySQL Server
$con = mysqli_connect($hostdb,$userdb,$passworddb,$db) or die ("could not connect");
session_save_path('../login/sessions');
require_once('functions.php');
?>
Figured out the problem guys for some reason when i was storing the variables on escaping the string there was spaces attached to the variable. thanks for the help guys.

MySQL and INSERT IGNORE

I am trying to read from a database in MySQL and insert my data in another database in MySQL .
my first table is like this
CREATE TABLE IF NOT EXISTS `link` (
`_id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(30) COLLATE utf8 DEFAULT NULL,
`time` varchar(20) COLLATE utf8 DEFAULT NULL,
`link` varchar(100) COLLATE utf8 DEFAULT NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6149 ;
and the second table is
CREATE TABLE IF NOT EXISTS `country` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(15) CHARACTER SET utf8 NOT NULL,
`Logo` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Name_3` (`Name`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8457 ;
There are about 6114 rows in first table that I'm trying to insert to second using this code
<?php
$tmp = mysqli_connect(******, *****, ****, *****); // First table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$main = mysqli_connect(*****, *****, ****, ******); //Second table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$req = "SELECT country FROM link";
$result = mysqli_query($tmp, $req) or die( mysqli_error($tmp) );
echo "-> ".mysqli_num_rows($result)."<br>";
while ($row = mysqli_fetch_array($result)) {
$con = $row["country"];
$req = "INSERT IGNORE INTO country (Name) VALUES ('$con')";
mysqli_query($main, $req) or die( mysqli_error($main) ) ;
}
?>
problem is the php code works but for 6114 take a very long time which I can't afford .
what is causing the code to take this long to work ? is it the "INSERT IGNORE" ?
is there any way I can do this faster ?
Since the databases are on the same server, you can simply use INSERT ... SELECT (which avoids having to bring the data into PHP and loop over the results executing separate database commands for each of them, so will be considerably faster):
INSERT INTO db2.country (Name) SELECT country FROM db1.link
you can try a create an index on column "country" of table Link.

Categories