MySQL Not creating Table through PHP - php

I'm currently working on a PHP/MySQL ranking system, but I've come into a problem with my CREATE TABLE statement.
Here's my code:
mysql_select_db("DB1");
$numrows = "SELECT COUNT( * ) FROM information_schema.tables WHERE table_schema = 'DB1'";
if($numrows > 1){
if($numrows > 2){
$table = rand(1, $numrows);
}else{
$table = rand(1, 2);
}
}else{
$table = rand(1, 1);
}
$checkForTable = mysql_query("SELECT 1 FROM $table LIMIT 1");
if($checkForTable){
$query = "INSERT INTO $table (name,score) VALUES($name, $score)";
$result = mysql_query($query);
mysql_select_db("DB2");
$query2 = "INSERT INTO Leaderboard (name,score) VALUES($name, $score)";
$result2 = mysql_query($query2);
mysql_select_db("DB1");
if($result && $result2){
echo "<h4 style='color:green;'>Your Score Has Been Inserted</h4><hr/>";
}else{
echo "<h4 style='color:red;'>We encountered an error while inserting your data </h4><hr/>";
}
}else{
$newtable = "CREATE TABLE $table (
id bigint AUTO_INCREMENT NOT NULL,
name varchar(255) NOT NULL,
score bigint(20) NOT NULL,
PRIMARY KEY('id')
)";
$result = mysql_query($newtable);
if($result){
$query = "INSERT INTO $newtable (name,score) VALUES($name,$score)";
$result = mysql_query($query);
mysql_select_db("DB2");
$query2 = "INSERT INTO Leaderboard (name,score) VALUES($name, $score)";
$result2 = mysql_query($query2);
mysql_select_db("DB1");
if($result && $result2){
echo "<h4 style='color:green;'>Your Score Has Been Inserted</h4><hr/>";
}else{
echo "<h4 style='color:red;'>We encountered an error while inserting your data </h4><hr/>";
}
}else{
echo "TableNotCreatedException: " . mysql_error();
}
}
When I try out the code I get:
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 '1 ( id bigint AUTO_INCREMENT NOT NULL, name varcha' at line 1
I've been trying to figure this out for a while but I've had no luck. Please Help!

That's because your $table variable contains a value 1 which you are using as table name and so your query becomes
CREATE TABLE 1(....
Per MySQL Documentation it says
Identifiers may begin with a digit but unless quoted may not consist
solely of digits.
Also, your quoting the column name as seen below
PRIMARY KEY('id')
It should rather be
PRIMARY KEY(`id`)

Related

Sending information from a newly created record to a different MySQL table

I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else

PHP / MySQL - Write and check UPPERCASE in database

I have the following code to write the name and score of a player into a highscore table. How can I write the 'name' in uppercase into the database?
if(isset($_GET['name']) && isset($_GET['score'])) {
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['score']));
$checkExist = mysql_query("SELECT `name`, `score` FROM `$tbl_name` WHERE `name` = '$name'");
$row = mysql_fetch_assoc($checkExist);
if (mysql_num_rows($checkExist) > 0){
if ($score > $row['score']){
$sql = mysql_query("UPDATE `$tbl_name` SET `score` = '$score' WHERE `name` = '$name'");
} else {
// ERROR MSG: Your new score is lower.(not updating the database)
}
} else {
$sql = mysql_query("INSERT INTO `$tbl_name` (`id`,`name`,`score`) VALUES ('','$name','$score');");
}
$name = strtoupper(strip_tags(mysql_real_escape_string($_GET['name'])));
http://php.net/manual/en/function.strtoupper.php
Either use strtoupper() in PHP, or UPPER() in MySQL: both do exactly the same, it's up to you.

Solve with only one query?

I have the following table:
CREATE TABLE list(
country TINYINT UNSIGNED NOT NULL,
name VARCHAR(10) CHARACTER SET latin1 NOT NULL,
name_index INT UNSIGNED NOT NULL,
UNIQUE KEY(country, name), PRIMARY KEY(country, name_index)) ENGINE = INNODB
I want to:
Given: ($country, $name, $new_index)
Check if a row with country = $country && name = $name exists.
If the row exists, get the index $index = name_index.
If the row doesn't exist, add it and then get the index.
I can do the following using many queries, but I am looking for an efficient way to do it, using only one query. Is this possible?
It's not possible with only one query.
You CAN do this:
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
$sql = "INSERT INTO (your table) (country, name)
VALUES('$country','$name')";
$query = mysql_query($sql);
$check = mysql_num_rows($query);
if($check > 0) {
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
echo "Error occured while trying to insert new row";
}
}
Hope this helps :).

Move with php one row to another in database tables

i'm using php to make some mods on my database, i have two identical tables and i want to move one row from the first table to the second one how can i do that using pure php and mysql.
that is how my tables looks like
CREATE TABLE users (
username varchar(30) primary key,
password varchar(32),
userid varchar(32),
userlevel tinyint(1) unsigned not null,
email varchar(50),
timestamp int(11) unsigned not null
);
and here is my php code so far
function procMoveUser(){
global $session, $database, $form;
/* Username error checking */
$subuser = $this->checkUsername("user");
/* Errors exist, have user correct them */
if($form->num_errors > 0){
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$session->referrer);
}
/* move the user */
else{
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONT."VALUES ($array['user'], $array['password'], $array['userid'] , $array['userlevel'] , $array['email'] , $array['timestamp'])";
$second_result = $mysqli->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
}
}
First, SELECT * FROM the first table for the row that you want to move. Then, as suggested above, run an INSERT statement with the values from the first table.
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
$result = $mysqli->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO second_table VALUES ($array['user'], $array['something'])";
$second_result = $mysqli->query($second_query);
if($second_result){
// it worked!
}
}
}
Maybe this will help: Copy an existing MySQL table to a new table

How can i escape MySQL 'Unable to jump row 0' error?

My question is how can I be sure of a row that I'd like to return is exists? I don't want to suppress it with PHP's # option or count rows before every query to find out the row is exists or not.
So there's a simple query like this:
"SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
and the table cannot contain the row with id 234.
You don't have to count rows before every query - generally you do it after.
What about something like this
$query = "SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
// do something because it was found
}
You're probably using mysql_result() to fetch the fields. Consider mysql_fetch_array instead. It returns FALSE if there are no more rows to fetch.
<?php
$mysql = mysql_connect('..', '..', '..') or die(mysql_error());
mysql_select_db('..', $mysql) or die(mysql_error());
$query = "SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
$result = mysql_query($query, $mysql) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo 'no such record';
}
else {
echo $row['title'], ' ', $row['id'];
}

Categories