MySQL and PHP Error - mysql

I have this code to create a database based off of a random number.
<?php
$con = mysql_connect("localhost","soociali","[censored]");
$databasename = rand(5, 7);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE $databasename",$con))
{
echo "Database created, called $databasename";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
However, I get this error: Error creating database: 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 '6' at line 1

Wrap your database name in ` marks:
if (mysql_query("CREATE DATABASE `$databasename`",$con))
The query "CREATE DATABASE 6;" is confusing MySQL as it's expecting an alphanumeric database name rather than what looks like a straight integer to it.

The name of your database will be parsed as a number. Just put betwwen backticks like this :
mysql_query("CREATE DATABASE `$databasename`",$con)

Related

mysql select - CONCAT no longer working with MariaDB upgrade

This code is part of a database search autocomplete function. It was coded a while ago but the database has since been upgraded from mysql to MariaDB.
This is the part of the code giving an error.
$sql = 'SELECT tree_id, tree_common_name, tree_botanical_name FROM all_trees';
for($i = 0; $i < $p; $i++) {
$sql .= 'WHERE CONCAT(tree_common_name,tree_botanical_name) LIKE ? ';
}
$stmt = $conn->prepare($sql);
if($stmt === false) {
$user_error = 'Wrong SQL: ' . $sql . '<br>' . 'Error: ' . $conn->errno . ' ' . $conn->error;
trigger_error($user_error, E_USER_ERROR);
}'
The error message
PHP Fatal error: Wrong SQL: SELECT tree_id, tree_common_name, tree_botanical_name FROM all_treesWHERE CONCAT(tree_common_name,tree_botanical_name) LIKE ? <br>Error: 1064 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 '(tree_common_name,tree_botanical_name) LIKE ?' at line 1 in /home/wiwi1740/public_html/includes/autocomplete.php on line 73
I've looked at using
$sql .= 'WHERE CONCAT_WS(' ',tree_common_name,tree_botanical_name) LIKE ? ';
but still throws an error.
Any tips would be appreciated. This code originally came from someone else that I adapted for my client.

I have an SQL syntax error when inputing data

I'm a beginner programmer and I'm getting a problem that I cannot seem to overcome. I predict it's a small syntax error but I don't know.
The code I'm using is the following:
<?php
$x=$_POST['firstname'];
$y=$_POST['lastname'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname="db1";
//Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT INTO 'user' ('fname', 'lname') VALUES ('$x','$y')";
if ($conn->query($sql) === TRUE) {
echo "New record created succesfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Once I press submit to input the data the following error comes up:
Connected successfullyError: INSERT INTO 'user' ('fname', 'lname') VALUES ('rty','rty')
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 ''user' ('fname', 'lname') VALUES ('rty','rty')' at line 1
Any help? Thanks in advance.
update your query replace single quote(') from table name and column name with (`), Like
$sql = "INSERT INTO `user` (`fname`, `lname`) VALUES ('$x','$y')";

SQL error text giving me a different value that the actual value

This is the line of code that is causing the error:
$result = $mysqli->query("SELECT * FROM 'accounts'.'users' WHERE email='$email' AND hash='$hash' AND active='0'") or die($mysqli->error);
and this is the error that shows:
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 ''accounts'.'users' WHERE email='testemail#email.com' AND hash='76dc611d6eba' at line 1
However, if I print the value of hash I get this "76dc611d6ebaafc66cc0879c71b5db5c" the value that I want to search with and the value that is stored in the database. I am not sure if it is just being shortened for the error message of if something else is happening.
Try changing from ' (apostrophe) to ` (backtick) or simply removed the single quotes from db/table name, so your query looks like this:
SELECT * FROM `accounts`.`users` WHERE email='$email' AND hash='$hash' AND active='0'
Try removing quotes around database and table name
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$result = $mysqli->query("SELECT * FROM accounts.users WHERE email='$email' AND hash='$hash' AND active='0'") or die($mysqli->error);

Why do I get this SQL syntax error? - Syntax error or access violation: 1064

Why do I get this error: SQLSTATE[42000]: Syntax error or access violation: 1064 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 '' at line 1?
<?php
include'model.php';
global $db;
try {
$sql ='SELECT accounts.username '
. 'FROM accounts '
. 'WHERE accounts.username = '
.$_POST[username];
$stmt = $db->prepare($sql);
$stmt->execute();
$navList = $stmt->fetchAll();
$stmt->closeCursor();
header('location: ./view_cms.php');
} catch (PDOException $exc) {
echo $exc->getMessage();
// header('location: ./view_error.php');
exit;
}
?>
Because you need to wrap strings in single quotes in the WHERE clause. You also need to access $_POST entries with a quoted string key:
$sql = "SELECT accounts.username ".
"FROM accounts ".
"WHERE accounts.username = '".$_POST["username"]."'";
Plus, this is the reason why PHP based web software has a bad reputation. Sanitize your inputs, for heaven's sake!! Your prepare statement doesn't do anything as you're not using parameters (your statement is not a prepared statement).

MySQL column mismatch error on very basic query

So I'm getting this error:
Error: Column count doesn't match value count at row 1
(Very common, and I've checked through google, and my issue is that most of the issues are actual comlumn mismatches as it describes)
My location table has "user", "latitude", "longitude", "posttext", user and posttext are both varchar, and lat and long are int. For the time being, I'm just trying to insert values with user and posttext values. I've taken the query out of my php, and run it in the SQL part of phpmyadmin and it runs fine, so I'm not sure why I'm getting the error.
A php form supplies the post data from text boxes, and this is the php processing code:
<?php
error_reporting(E_ALL);
$username = $_POST['user'];
$textToPost = $_POST['textToPost'];
$con = mysql_connect("127.0.0.1","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test");
$sql= "INSERT INTO location(user, posttext)
VALUES ('.$username.,.$textToPost.')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
echo $username;
echo $textToPost;
?>
So I'm hoping it's a very basic syntax error on my part, but could someone help?
You're missing some quotes:
$sql= "INSERT INTO location(user, posttext)
VALUES ('".$username."','".$textToPost."')";
Shouldn't the query be like this?
$sql= "INSERT INTO location(user, posttext)
VALUES ('".$username."','".$textToPost."')";
Try with
$sql= "INSERT INTO location(user, posttext)
VALUES ('".$username."','".$textToPost."')";
Remember you MUST always sanitize user input before using it in a query!!
It could be better using prepared statements...