Trouble specifying my tablename inside query because of dot notation - php

I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";

You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.

I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.

Related

PHP - MySql Array

I am new to PHP and I am having trouble solving this: I have an array (PHP) that looks like this
"tandemArray":["English", "German"]
As seen in my LogCat (Eclipse, I return the array to the Android client and log it in Eclipse). I want to query the database with a string similar to:
$myQuery = "SELECT id
FROM my_users
WHERE // some code
AND Tandem_Tongue IN ("English", "German"); // The tandemArray
I've tried different approaches but without success. For instance:
$myQuery = "SELECT id
FROM my_users
WHERE // some code
AND Tandem_Tongue IN ("' . implode('","', $tandemArray) . '")';
I would greatly appreciate any help!
The code uses mismatching quotes and double-quotes in your shown approach; try reversing the ' and " to be like this:
$myQuery = "SELECT id"
. " FROM my_users"
. " WHERE 1=1" // using an actual WHERE-clause
. " AND Tandem_Tongue IN ('" . implode("','", $tandemArray) . "')";
The correct code is provided by ChrisForrence:
$myQuery = "SELECT id
FROM my_users
WHERE // some code
AND Tandem_Tongue IN ('" . implode("','", $tandemArray) . "')';
The problem was in quotes mismatch.
Not positive but I think you've mismatched the quotes and periods in your example. Should be more like:
$myQuery = "SELECT id
FROM my_users
WHERE // some code
AND Tandem_Tongue IN (".implode("','",$tandemArray).")';
I just used single quotes around the array elements since that is usually easier for me to decipher in mysql queries. Eg. 'English', 'German' You'll need to adjust if you need double quotes.

I'm new to PHP and MySQL. I cannot figure this simple system out

<?php
$db = new mysqli("localhost","root","password","eme");
if($db->connect_errno){ echo "Not connected."; exit();}
echo $db->query("SELECT * FROM users") . "<br>";
echo $_POST[FirstName] . " " . $_POST[LastName];
$db->query("INSERT INTO users (FirstName, LastName) VALUES ('$_POST[FirstName]','$_POST[LastName]')");
echo $db->query("SELECT * FROM users") . "<br>";
?>
I cannot figure out why this code doesn't work. The only line that outputs anything is "echo $_POST[FirstName] . " " . $_POST[LastName];"
My database has a "users" table and the database is called eme. The database connects properly.
There is currently no data in the database. I figured I could add some with "INSERT," but it's failing.
You have several problems:
The query() method of mysqli returns a mysqli_result object. you need to use one of it's methods to get the actual data back from the query. For instance fetch_assoc()
In your insert, you need to either assign $_POST['FirstName'] to a variable, or explicitly add it to the string.
ie.
"INSERT INTO users (FirstName, LastName) VALUES ('" . $_POST['FirstName'] . "','" . $_POST['LastName'] . "')"
or
$first = $_POST['FirstName'];
$last = $_POST['LastName'];
"INSERT INTO users (FirstName, LastName) VALUES ('" . $first . "', '" . $last . "')"
You should also sanitize the data before inserting it to prevent major security threats.
Lastly, it's not a bug per se, but you should always use a string or integer value for an array index.
ie. You have $_POST[FirstName], it should be either $_POST['FirstName'] or $_POST["FirstName"]
It will still work, but the interpreter thinks it's a constant, which isn't defined, so assumes the literal value, throwing a warning (maybe notice, can't remember offhand). It's unnecessary overhead.
Try this...
$db->query("INSERT INTO users (FirstName, LastName) VALUES('".$_POST['FirstName']."','".$_POST['LastName']."')");
For more info on Quotes, look over this link - What is the difference between single-quoted and double-quoted strings in PHP?

Escaping a string being inserted into Mysql

I have tried all combinations of single quotes, double quotes etc but the following code keeps erroring with sql syntax error. The en and cy are paragraphs of text. I think I must be missing something obvious but I cant see it. Any suggestions?
$insert_dana = mysql_query("UPDATE Contributor (Summary_en,Summary_cy) VALUES ('" . mysql_real_escape_string($insert[en][0]) . "','" . mysql_real_escape_string($insert[cy][0]) . "') WHERE id='$insert[id]'");
You mixed insert and update statement syntax. Use this one
$insert_dana = mysql_query("UPDATE Contributor set Summary_en = '" . mysql_real_escape_string($insert[en][0]) . "', Summary_cy = '" . mysql_real_escape_string($insert[cy][0]) . "' WHERE id='$insert[id]'");
you're confusing the UPDATE- and the INSERT-syntax. for UPDATE, it's like:
UPDATE
table
SET
field = 'value'
WHERE
...
while an INSERT looks like:
INSERT INTO
table
(field)
VALUES
('value')
you can't write an UPDATE with (field) VALUES ('value')-syntax.

MySQL - Delete a row, how?

Can anyone show me a query in MySQL that would delete rows from all available columns.
I use this to insert rows:
$sql = "INSERT INTO " . KEYS . " // KEYS is a constant
(key, user_id, time, approved)
VALUES ('" . $randkey . "', '" . $user_id . "', '" . $time . "', '0')";
I need the opposite of this now, delete created rows.
delete from <table> where ....
Keep in mind that the delete statement is always for an entire row.
Using similar syntax sql = "DELETE FROM " . KEYS . " WHERE 1=1";
Replace 1=1 with the conditions for the row you want to delete or it will delete all rows.
Also, it's good to get out of the habit of just dropping variables into SQL as soon as possible, because it will open your code up to SQL Injection attacks. Look into using parameterized queries.

Odd Mysql issue on insert

Hy all,
Not sure what's going on here, but if I run this:
$query = 'INSERT INTO users
(`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES
("'. $user_id . '", "' . $first_name .'", "'. $second_name . '", "' . $date . '", "' . $date . ");';
$result = mysql_query($query);
I get no return, but if I change it to this it's fine:
$query = 'INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES ("21021212", "Joe", "Bloggs", "20090202", "20090202");';
$result = mysql_query($query);
User id = bigint(20)
first name = varchar(30)
second name = varchar(30)
date = int(8)
At first I thought it was a issue with the vars but they are exactly the same and still don't work.
Any help appreciated.
Get into the habit of escaping all database inputs with mysql_real_escape_string- really, you should use some kind of wrapper like PDO or ADODb to help you do this, but here's how you might do it without:
$query = sprintf("INSERT INTO users ".
"(id, first_name, second_name, register_date, lastlogin_date)".
"VALUES('%s','%s','%s','%s','%s')",
mysql_real_escape_string($user_id),
mysql_real_escape_string($first_name),
mysql_real_escape_string($second_name),
mysql_real_escape_string($date),
mysql_real_escape_string($date));
$result = mysql_query($query);
and also check for errors with mysql_error
if (!$result)
{
echo "Error in $query: ".mysql_error();
}
What's the result from "mysql_error()"? Always check this, especially if something doesn't seem to be working.
Also, echo out $query to see what it really looks like. That could be telling.
Maybe the value of $date was "1111'); DELETE FROM users;"?
Seriously though? The problem is that isn't how you interact with your database. You shouldn't be passing in your data with your query. You need to specify the query, the parameters for the query, and pass in the actual parameter values when you execute the query. Anything else is inefficient, insecure and prone to bugs like the one you have.
By using PDO or something that supports parametrized queries, you'll find these kinds of issues go away because you are calling the database property. It is also much more secure and can speed up the database.
$sth = $dbh->prepare("INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`) VALUES (?,?,?,?,?)")
$sth->execute(array($user_id ,$first_name , $second_name , $date, $date ));
In addition to echoing the query and checking mysql_error() as #GoatRider suggests:
Are you escaping your data properly? See mysql_real_escape_string()
You shouldn't end your queries with a semicolon when using mysql_query()
in $query = 'INSERT INTO users (id, first_name, second_name, register_date, lastlogin_date) VALUES ("' . $user_id . '", "' . $first_name . '", "' . $second_name . '", "' . $date . '", "' . $date . '");
are u giving the correct date format?? it might be the issue. otherwise the syntax is all fine.

Categories