Can't convert URL into hyperlink to store in MySQL - php

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));
}

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.

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.

PHP not inserting some values into MySQL database

I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Sometimes an input field in the HTML form will be left blank and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:
Home team: Blue team
Away team: [blank]
Result: Won
The following is inserted into my database:
Home team: Blue team
Away team: ' '
Result: Won
What I want to be inserted/not inserted is:
Home team: Blue team
Away team: NULL
Result: Won
I've hunted hours for a solution. Can anyone help? Thank you.
Well it will insert the final value only , because you are executing the $sql and the last values of $sql is "INSERT INTO scores (result) VALUES ('$_POST[result]')"; You are overiding the previous values by putting same variable name.
Also (!empty($_POST[hometeam])) remove the !empty if the fields can be blank sometimes.
You are overwriting your SQL statements each time. Beacue your 'result' field isn't blank, you are setting your SQL statement to:
"INSERT INTO scores (result) VALUES ('$_POST[result]')"
This is the only statement which is then being executed - your other values are being ignored as they are not part of this statement.
What you need to do is set up your variables first:
$hometeam = isset($_POST['hometeam']) ? $_POST['hometeam'] : NULL;
$awayteam = isset($_POST['awayteam']) ? $_POST['awayteam'] : NULL;
$result = isset($_POST['result']) ? $_POST['result'] : NULL;
You can then do your database interaction:
$sql = "INSERT INTO scores hometeam, awayteam, result VALUES $hometeam, $awayteam, $result";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
I should say that I haven't included any security on this - you should look into PDO or prepared statements to make sure your database isn't open to SQL Injection.
Hope this helps!
First off, there's a huge security flaw in this code, which is not sanitizing your inputs. A user could insert whatever they like and it's executed on the DB without any checking. This is bad.
At the very least, you should be using something like mysql_real_escape_string(), even though even that is not exactly the best thing for the job (Google PHP + PDO for example).
Secondly, you're actually executing one query using one variable. If $_POST['result'] is set, then $sql will always be the last value. What you might want to do is make the query like so:
$query = 'INSERT INTO scores ('.$fields.') VALUES ('.$values.')';
And construct the $fields and $values variables using your if(!empty( .. )) code.
But to reiterate SANITIZE YOUR INPUTS
3 insert into statements will insert 3 records, with unspecified fields left as null or default.
you must use 1 insert into statement, something like:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
#$sql="INSERT INTO scores (hometeam,awayteam,result) VALUES ('{$_POST[hometeam]}','{$_POST[awayteam]}','{$_POST[result]}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
here, unspecified values will come as empty string, if that is a problem, first assign them to 3 seperate variables with ifs (e.g. set empty ones to null), then use them
I think there is some problem with the declaration of name of your input field in you html form. Make sure, $_POST[hometeam] must be the same input name in your form
Example:
In your form
<input type="text" name="hometeam" value="" />
In your PHP
if (!empty($_POST[hometeam])) {
$sql="INSERT INTO scores (hometeam) VALUES ('$_POST[hometeam]')";
}
And also, please use addslashes or mysql_real_escape_string in your post values before adding it on the database.
Look at this link below:
http://php.net/manual/en/function.addslashes.php
http://php.net/manual/en/function.mysql-real-escape-string.php
if (!empty($_POST['hometeam'])) {
$sql="INSERT INTO scores (hometeam) VALUES ('" . $_POST['hometeam'] . "')";
}
Notice the single quotes around the 'hometeam' part.
You should also clean that using mysql_real_escape_string($_POST['hometeam']).
Bear in mind this will create upto 3 rows for each call, if you want to have a row like scores (hometeam, awayteam, result) you'll need to construct your query differently (i.e. a single query not 3 seperate ones).

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