PHP MySQL Query Insert consistent error - php

//--------------------------------------------------------------------------
// php script for adding data from mysql database
//--------------------------------------------------------------------------
$ip = $_GET['ip']; //for debugging sake, will be POST from Ajax
$key = substr(md5(microtime()),rand(0,26),5); //random referral ID - will implement exist analysis
echo $ip; //debugging
$dbhost = 'localhost';
$dbuser = user;
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $conn);
$tbl_name = "refs";
$sql="INSERT INTO $tbl_name(ip, key)VALUES('frfr', 'grgr')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
I'm not sure if it's my Digital Ocean server or what, but the only syntax my PhpMyAdmin will accept as a query is as INSERT INTOrefs(ip,key) VALUES ("insert","432")
with the double quoted values. I cannot seem to get this implemented in the PHP without getting a flat out error or an Unknown column in 'field list' error.
Similar questions suggest junk non-printable characters from copy-paste, however I've retyped my code within the editor. Thanks for all the help
I'm creating a basic referral system by the way, storing requested IP's in 'refs' table with a key, or id.

key is a reserve word and thus needs to be escaped using backtique. Along with that you have spacing issue as well. Your query should looks like below
INSERT INTO refs(ip,`key`) VALUES ('insert','432')
Never use a reserve word as column or table name. if in doubt, then escape all the columns present in query.
Start referring MySQL Documentation for more inforamtion. It's way easier than posting it as question in stackoverflow.

Related

Creating a mysql database with "." in the name (using php) [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been having some trouble recently with trying to automate new database creations with a php script.
Basically, the script takes the new login username and creates a database (and then insert some tables and data later on, which is also done via a php script).
I used to have to manually create the database, but now need to make it automated.
The issue is that I used to be able to just create a new database using the phpadmin "new database" function from the web GUI and put in names like "test1.siteA", "userb.siteB".
However, now that I've tried to do the same via php script, it keeps giving me the "You have an error in your syntax..." from my last "echo".
Main parameters are:
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
I've found that the error would disappear once I remove the .site part from the code (it still exist even if I combine the $dbname into 1 line).
According to some articles that I've found online, it seems that MySQL doesn't allow special characters like "." to be included in the database name.
It just seems very weird to me that the ".site" can be added manually through phpMyadmin while the php/mysqli script doesn't allow this.
The full script is as follows (I'm sure it can be heavily improved, so any suggestions regarding that are also welcome):
<?php
define("_VALID_PHP", true);
require_once(APPPATH. "/libraries/init.php");
include (BASEPATH . "/database/DB_temp.php");
$row = $user->getUserData();
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
// Create connection
$conn = mysqli_connect($servernm, $usnm, $pasd);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check if DB exist
$sql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
$check = mysqli_query($conn,$sql)
or die("Connection failed: " . mysqli_connect_error());
while($row = mysqli_fetch_array($check,MYSQLI_NUM))
{
$dbval = $row[0];
}
if ($dbval == "0")
{
$createsql = "CREATE DATABASE '$dbname' ";
}
if ($dbval == "1")
{
$createsql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
}
if (mysqli_query($conn, $createsql)) {
Echo "Completed. DBVAL= " .$dbval ;
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
?>
PHP version: 5.6.18
phpmyadmin: 4.5.4.1
Ubuntu 14.04
Apologies if I've made some posting errors on here. Do let me know about them and I'll try to correct it as much as I can. Any help is greatly appreciated!
. is a meta character in SQL, use to separate db/table/field names:
SELECT foo.bar.baz FROM sometable
^---------- database 'foo'
^------- table 'bar'
^--- field 'baz'
You should NOT be using metacharacters in any identifiers. It just leads to pain later on, and having to do stuff like:
SELECT `foo.bar`.baz.qux FROM ...
^^^^^^^^^--------- database 'foo.bar'
^------ table 'baz'
^-- field 'qux'
So you can use backticks if you absolutely have to, but you shouldn't be doing this in the first place.
try wrapping the database name with back ticks.
$dbname .= '`.site`';

Error message: Database Query failed

For some reason, the following code inside the query works in my MySQL command console, yet when I try to run it as a Query in PHP, something keeps going wrong and I'm not sure what. Here is the code I've done so far.
//2. Perform database query
$query = "SELECT skills.element_id, content_model_reference.element_id, element_name FROM skills, content_model_reference WHERE (skills.element_id = content_model_reference.element_id)";
$result = mysql_query($query);
//Tests if there was a query error
if(!$result){
die("Database query failed.");
}
Is there something preventing the code that worked in MySQL (The line with SELECT) from working, or is my syntax somehow wrong?
EDIT: So it's saying I didn't select a database. Yet I thought I had. Here is the code above it:
//1. Create a database connection
$dbhost = "host"; //Host: Can be either an IP address, or a domain (like google.com).
$dbuser = "user";//User: The user that is connecting to the database.
$dbpass = "pass";//Password: This is the password that the user is using.
$dbname = "db";//Name: This is the name of the database.
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);//The value, 'handle,' is the connection.
//Test if connection occurred. Die ends the program/php, and in this case, also prints a message
if(mysqli_connect_errno()){
die("Database connection failed: ".
mysqli_connect_error().
" (". mysqli_connect_errno() . ")"
);
}
Like I said, the error message I am getting is pertaining only to the query, the server is fine with my database connection.
You're using mysqli_* for the connection, but you're using mysql_* for the QUERY... don't think you can do that, has to be one or the other (MYSQLI_ preffered). Also the query should be:
$result = mysqli_query($connection,$query);

SQL Update code issue/PHP injection

I am having an issue with my SQL Update script.
It prints "Motto Changed" but doesn't update the row. My code is all correct according to many tutorials. Please Help
$sql="UPDATE loadout SET motto='".$_POST['motto']."' WHERE steamid='".$steamid."'";
UPDATE AGAIN:
<?php
require "../requires/php/steam.php";
$dbhost = '**';
$dbname = 'battlefield';
$dbuser = 'battlefield';
$dbpass = '**';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
$authserver = bcsub( SteamID(), '76561197960265728' ) & 1;
$authid = ( bcsub( SteamID(), '76561197960265728' ) - $authserver ) / 2;
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
mysql_select_db($dbname, $con);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "Motto Changed";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo"Motto changed on {$n} row(s)";
mysql_close($con)
?>
Never interpolate $_POST variables directly into SQL strings. You can't trust $_POST variables, they may easily contain characters that modify your SQL syntax, and that's what causes SQL injection vulnerabilties.
The weird thing is that you create an escaped version as $motto and then you never use it (as per comment from #Arth).
Always escape strings that you interpolate into SQL, even if you think they are "safe." For example, your $steamid contains only literal text that you control, plus a couple of integers. That should be safe, but what if some other developer changes the format of a steamid next year? If you escape it, you can't go wrong.
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
Of course, the best practice is to use query parameters. You are using PHP's deprecated mysql extension, which doesn't support query parameters. But I understand if you're not ready to rewrite a lot of code to switch to PDO. When you are, follow examples in How can I prevent SQL-injection in PHP?
Another issue: if you want to know if the UPDATE affected rows, don't assume it did just because the UPDATE didn't return an error. It's not an error if your condition in your WHERE clause simply matched zero rows. It's also not an error if the UPDATE matched a row, but the motto already contained the string you tried to set.
After the UPDATE, check the number of affected rows:
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo "Motto changed on {$n} row(s)";

Nesting MySQLI Queries

I am trying to pull a number from one table inside a database, and then use that number to process a query on another table in the same database.
The code doesn't spit out any errors - it just doesn't return a string! I am trying to understand mysqli and the whole array structure, but I'm having difficulty figuring out why this isn't working. I believe I am trying to successfully turned the original array into a string for use in the second query, which I also translate into a string for the echo. It's just that for some reason it's not printing anything! If I take out the nested loop then it prints the active_event number just fine. I'm at a loss!
<?php
$DBServer = 'localhost';
$DBUser = 'user';
$DBPass = 'pass';
$DBName = 'database';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$get_active_event = mysqli_query($conn, "SELECT active_event FROM asp_config");
while($active_event = #mysql_fetch_assoc($get_active_event)){
$get_event_name = mysqli_query($conn, "SELECT * FROM asp_events WHERE id = {$active_event['active_event']}"); echo $get_event_name->fetch_object()->event_name;}
$conn->close();
?>
Thanks!
-Philip
I suggest to change the logic of your piece of code modifying you db schema in a more efficient way.
I'd fetch the results in a single query joining the two tables asp_config and asp_events or, even better, if possible get rid of asp_config and add a column is_activeor something like this to asp_events table.
Then you just have to cycle with while-loop without the second query because all you need to know is in the first results set.
Be careful to use the error suppression (#) you need to know if there is an error and handle it. Suppress without knowing it's a bad pratice
Unfortunately joining the two tables isn't an option, and I have other queries that need to use the same type of functionality so merging all of the tables into one just isn't doable. That all said, I did figure it out. I think the biggest issue was that I wasn't exiting out of the SQL mode before trying to insert the PHP variable, so I ended up querying a null row which returned a blank dataset. The final code I used is:
<?php
$DBServer = 'localhost';
$DBUser = 'user';
$DBPass = 'pass';
$DBName = 'actionsports';
$con = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($con->connect_error) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$get_active_event = mysqli_query($con,"SELECT * FROM asp_config");
while($active_event = mysqli_fetch_array($get_active_event))
{
$get_event_name = mysqli_query($con, "SELECT * FROM asp_events WHERE id=('" .$active_event['active_event'] ."')");
if ($get_active_event === false) {
exit("Error: " . mysqli_error($con));
}
while($event_name = mysqli_fetch_array($get_event_name))
{ echo $event_name['event_name'] ;}}
$con->close();
?>
In this case I do have a query loop inside another loop, and it does return the correct data. It might not be the prettiest code, but it works and is what is required for my situation.
Thanks for the help!

postgres update through php

I am a complete novice at php and postgres. I have been searching all over the net for an answer but no joy! I have a postgres table called workorders. It has a primary key (ident). I am trying to up date it using a php script/program. Basically the ident is the workorder number. I have written a php script where i type in the workorder number, post it to another php file, which connects to the database, finds the ident that matches and updates it by adding 'paid' to a column called paid. I have made it work using INSERT into, but it will not allow duplicate keys so that is why i am trying to use update. When I do, it says "unexpected T_CONSTANT_ENCAPSED_STRING"
Help would be greatly appreciated.
<?php
include('adodb5/adodb.inc.php');
$DB = &ADONewConnection('postgres');
$DB->PConnect('host=localhost port=5432 dbname=test user=postgres password=secret');
if (!$DB) {
die("Error in connection: " . pg_last_error());
}
$arr = array( array('paid',$_POST['$invoice']), );
$ok = $DB->Execute('insert into workorders (paid, ident) values (?,?)',$arr);
if (!$ok) {
die("Invoice not posted. " . pg_last_error ());
}
?>
If I use this I can insert into my database. If I replace INSERT into with UPDATE or pg_update I get errors.
Have now seen your code, which looks fine.
T_CONSTANT_ENCAPSED_STRING is often the result of not escaping quotation marks when used in strings. But I am not seeing that here. Can you post the example that does not work?
include('adodb5/adodb.inc.php');
$DB = &ADONewConnection('postgres');
$DB->PConnect('host=localhost port=5432 dbname=test user=postgres password=secret');
if (!$DB) {
die("Error in connection: " . pg_last_error());
}
$arr = array( array('paid',$_POST['$invoice']), );
$ok = $DB->Execute('insert into workorders (paid, ident) values (?,?)',$arr);
if (!$ok) {
die("Invoice not posted. " . pg_last_error ());
}

Categories