PHP - MySql Array - php

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.

Related

Trouble specifying my tablename inside query because of dot notation

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.

data from a json object not inserting into mysql in php foreach loop

I am trying to insert the results from a json array into MySQL using
foreach ($feed->items as $item) {
$query = "insert into data(id,url,keyword)values ($item->id, $item->url,$item->kind)";
$result = mysql_query($query);
echo $result;
}
I have confirmed the database details are OK and the $items are correct.
Can anyone point me in the right direction? I am fairly new to PHP so any help is appreciated.
You need to escape the values in the SQL:
$query = "insert into data(id,url,keyword)values ('" . mysql_real_escape_string($item->id) . "', '" . mysql_real_escape_string($item->url) . "' , '". mysql_real_escape_string($item->kind) . "')";
this adds quotation marks ' around the variables so that the SQL can be parsed at all
This prevents SQL injection.
You need to wrap your variabels in your query :
$query = "insert into data(id,url,keyword)values ('{$item->id}', '{$item->url}', '{$item->kind}')";

Can't convert URL into hyperlink to store in MySQL

Sorry to be back two days in a row. I spent the whole day yesterday reading on this site and others and I'm just stuck. The only thing I found close was for C++. I'm building a data base for my DVDs and Movies so I and my friends can search by Title, Actors, etc. With help here yesterday, I was able to get a data entry form working. One of the fields is a hyperlink to IMDB for info about the movie. I want to just be able to paste the URL into the form but have it stored as a full hyperlink in MySQL. When it comes up in the results pages it just appears as a link I can click on and go to the IMDB page.
This is what I've come up with so far. I get a syntax error if I include the "target="_blank"> but if I take that out there's no syntax error but I get the "Error X" with no error code and no entry into the database. Is there any way I can get this to work? Thanks in advance.
// Make link info into hyperlink for database
$url = ('$_POST[link]');
$f_link = "IMDB Movie Page";
// Write data to table.
$sql="INSERT INTO movies (Movies, Rating, Genre, Year, Actors, Time, Notes, Viewed, BitRate, link)
VALUES ('$_POST[Movies]','$_POST[Rating]','$_POST[Genre]','$_POST[Year]','$_POST[Actors]','$_POST[ Time]','$_POST[Notes]','$_POST[Viewed]','$_POST[BitRate]', $f_link)";
if (!mysqli_query($con,$sql))
{
die('Error: X ' . mysql_error($con));
}
To your question about the quotes:
consider the following sql:
$sql = "SELECT * from table1 where id = god";
mysql interpret got as some thing else than a string ('god' is different from got).
therefore you should type
$sql = "SELECT * from table1 where id = 'god'";
or
$value = 'god';
$sql = "SELECT * from table1 where id = '{$value}'";
or
$value = 'god';
$sql = "SELECT * from table1 where id = '" . $value . "'";
Note: in case the value is a Numeric (flaot, integer, ... ), then you don't neet the quote
$value = 12334;
$sql = "SELECT * from table1 where id = {$god}";
I recommend that you store the plain $url in the database without the HTML. If you later want to change your link you would have to work out how to update all your records... If you switch your code to just store the URL without adding HTML around it, it will fix the error (which is unescaped quoted).
When you retrieve the URL from the database, you can wrap it with your HTML and avoid that pain.
You are doing great to get started in just a couple of days with this - but you may need to have a think about SQL injection as even if you don't think someone will deliberately attack your page, you could accidentally cause problems if you don't parametrise your SQL - for example if someone accidentally types a ' into the form.
You need to escape quotes when you want to include them inside a quoted string.
$f_link = "IMDB Movie Page";
but you should also have quote around the URL
$f_link = "IMDB Movie Page";
Using single quotes to enclose makes it easier,
$f_link = 'IMDB Movie Page';
but bear in mind PHP doesn't parse the contents in this instance, which isn't a problem in that line because you've concatenated $url, which is the cleaner way.
Also note you're leaving yourself open to SQL injection be allowing those $_POSTs to be directly inserted into a SQL command.
Replace your code through:
$url = ($_POST['link']);
$f_link = "IMDB Movie Page";
// Write data to table.
$sql="INSERT INTO movies (Movies, Rating, Genre, Year, Actors, Time, Notes, Viewed, BitRate, link)
VALUES
('" . $_POST['Movies'] ."', '" . $_POST['Rating'] . "', '" . $_POST['Genre'] . "', '" . $_POST['Year']" . ', '" . $_POST['Actors'] ."', '" . $_POST['Time'] . "', '" . $_POST['Notes'] . "','" . $_POST['Viewed'] . "','" . $_POST['BitRate'] . "', '{$f_link}' )";
if (!mysqli_query($con,$sql))
{
die('Error: X ' . mysql_error($con));
}

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.

How do you insert a PHP constant into a SQL query?

I have a PHP file with my database configuration settings defined as constants, for example:
<?php
define(DB_HOST,"localhost");
define(DB_USERNAME,"root");
define(DB_PASSWORD,"password");
define(DB_NAME,"db_users");
define(DB_TABLE_1,"table_1");
define(DB_TABLE_2,"table_2);
?>
I obviously include the above file whenever I want to connect to my database..However, when I go to insert the table definition constants into the SQL query (see below) it doesn't seem to work. Do I need to properly escape the constant or concatenate it in some way?
$query = "SELECT users FROM DB_TABLE_1";
You'll have to use string concatenation (of any sort).
$query = "SELECT users FROM " . DB_TABLE_1;
constants will not interpolate into a string as variables can.
One hackish alternative is to use a variable function:
$const = 'constant';
$query = "SELECT users FROM {$const('DB_TABLE_1')}";
which'll execute the constant() function and return the constant's value, but that's generally not a good idea, if only for legibility's sake.
Just put it outside the quotes and it should work fine:
$query = "SELECT users FROM ".DB_TABLE_1;
I've found two ways.
1.-
define("VALUE1", "someValue");
$query = "SELECT * FROM TABLE WHERE `Column` /*=" . VALUE1 . "*/";
2.-
define("VALUE1", "someValue");
define("VALUE2", "otherValue");
$query = "INSERT INTO TABLE (`Column1`, `Column2`) VALUES (" . VALUE1 . ", " . VALUE2 . ")";
The backticks (``) I use because I'm using phpmyadmin, you might not need them.
I think this is easier:
$query = "SELECT users FROM '.DB_TABLE_1.'";
when using multiple tables:
$query = "SELECT TB_1.users, TB_2.names FROM '.TB_1.'
INNER JOIN '.TB_2.'
ON x=y";
Also, this is better:
define("DB_HOST","localhost");

Categories