This one has got me stumped. When I try to save something to the database that contains an apostrophe ('), it will save the sence up until then and after that it does not not. For example;
Say I am trying to save this: Report details Tim Cook's changes at Apple, for better or worse »
It saves: Report details Tim Cook
It saves to the database fine but only everything before the '
My code:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Any help as to why it might not be saving properly? I have tried mysql_real_escape_string but (if I am using it correctly) that does not seem to work.
Side note: What is the best way to secure the form above from attacks?
Update It is also doing it for " as well.
You need to call mysql_real_escape_string() after connecting to your database:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Change
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
to
$query = "INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')";
echo $query;
mysql_query($query);
And check out the actual query you are sending, easy to spot the problems then :)
Related
I'm trying to insert some data into a database, I have the following code which is connecting to the database but not inserting any results (just empty rows).
I know the below code doesn't work, I've just tried to explain in PHP what I want. The issue is with the data being held in an array such as $tweet['created_at'] and I need this in a variable format so I can insert it into the database.
Any help is greatly appreciated, thank you!!
if ($_GET) {
$conn = mysql_connect('localhost', 'user', 'pass')
or die (mysql_error());
$tweet['created_at']=$tweet_created_at;
$tweet['text']=$tweet_text;
$tweet['location']=$tweet_location;
$tweet['followers_count']=$tweet_followers_count;
$tweet['sentiment']=$tweet_sentiment;
mysql_select_db("db") or die(mysql_error());
mysql_query("INSERT INTO table (Created_at, Tweet, Location, Number_of_Followers, Semantic_Result) VALUES ('$tweet_created_at', '$tweet_text', '$tweet_location', '$tweet_followers_count', '$tweet_sentiment')", $dbconnect);
}
Mysql only understands SQL. So to insert an array into a mysql database you have to convert it to an sql statement. This can be done manually or by a library. The output should be an INSERT statement.
$columns = implode(", ",array_keys($tweet));
$values = array_map('mysql_real_escape_string', array_values($tweet));
$values = implode(", ", $values);
$sql = "INSERT INTO `table `($columns) VALUES ($values)";
You can do something like this:
if ($_GET) {
$conn = mysql_connect('localhost', 'user', 'pass')
or die (mysql_error());
$tweet['created_at']=$tweet_created_at;
$tweet['text']=$tweet_text;
$tweet['location']=$tweet_location;
$tweet['followers_count']=$tweet_followers_count;
$tweet['sentiment']=$tweet_sentiment;
mysql_select_db("db") or die(mysql_error());
mysql_query('INSERT INTO `table` (`'.implode('`,`',array_keys($tweet)).'`) VALUES ('.implode("','",array_map('mysql_real_escape_string',$tweet)).')');
}
I included mysql_real_escape_string because you should always escape your data. If your database still has empty data then check the character encoding and make sure that the fields in the database are defined properly. such as INT for followers, TEXT for 'text', etc...
Edit: I suspect you're trying to retrieve data from input fields. Make sure the form does not "POST" (<form method="post">) and that the field names match. you should also use $_SERVER['REQUEST_METHOD'] to determine request.
if the data is in the url. I.E: page.php?created_at=xxx&.... Then this works fine...
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$conn = mysql_connect('localhost', 'user', 'pass') or die (mysql_error());
$tweet['created_at']=$_GET['tweet_created_at'];
$tweet['text']=$_GET['tweet_text'];
$tweet['location']=$_GET['tweet_location'];
$tweet['followers_count']=$_GET['tweet_followers_count'];
$tweet['sentiment']=$_GET['tweet_sentiment'];
mysql_select_db("db") or die(mysql_error());
mysql_query('INSERT INTO `table` (`'.implode('`,`',array_keys($tweet)).'`) VALUES ('.implode("','",array_map('mysql_real_escape_string',$tweet)).')');
}
Cheers guys, I've used some of your suggestions and I've got it working.
I replaced:
$tweet['created_at']=$tweet_created_at;
with:
$created_at = mysql_real_escape_string( $tweet['created_at'] );
and used the implode attribute
Now it works fine!
Thanks!!!
I'm having to convert my inspection app to MySQLi but have been having many issues doing so since Amazon EC2 updated their MySQL
With not knowing much about php/mysql to begin with, I'm at a loss. Most of my searches have been way beyond what I understand.
This is what the file used to look like.
<?php
include("connect.php"); // Connect to RDS
$query="SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
$result=mysql_query($query);
$num = mysql_num_rows ($result);
$username = mysql_result($result,$i,"username");
$oldurl = mysql_result($result,$i,"oldurl");
$homedata = mysql_result($result,$i,"homedata");
$clientemail = mysql_result($result,$i,"clientemail");
$general_info = mysql_result($result,$i,"general_info");
$company_name = mysql_result($result,$i,"company_name");
$company_hours = mysql_result($result,$i,"company_hours");
$company_phone = mysql_result($result,$i,"company_phone");
$company_support_email = mysql_result($result,$i,"company_support_email");
$beyondscope = mysql_result($result,$i,"beyondscope");
mysql_close();
?>
This is what I have so far. One error I'm getting line 17 has unexpected ',' (comma), even that every line has the same setup.
Thanks in advance for any help with this.
<?php
include("connect.php"); // Connect to RDS
$query="SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
$result=mysqli_query($GLOBALS["___mysqli_ston"], $query);
$num = mysqli_num_rows($result);
$username = mysqli_fetch_array($result,$i,"username");
$oldurl = mysqli_fetch_array($result,$i,"oldurl");
$homedata = mysqli_fetch_array($result,$i,"homedata");
$clientemail = mysqli_fetch_array($result,$i,"clientemail");
$general_info = mysqli_fetch_array($result,$i,"general_info");
$company_name = mysqli_fetch_array($result,$i,"company_name");
$company_hours = mysqli_fetch_array($result,$i,"company_hours");
$company_phone = mysqli_fetch_array($result,$i,"company_phone");
$company_support_email = ($result,$i, "company_support_email");
$beyondscope = mysqli_fetch_array($result,$i,"beyondscope");
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
?>
UPDATE: To add connect.php
<?php
$hostname='.rds.amazonaws.com';
$user='username';
$pass='password';
$dbase='dbasename';
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect("$hostname" , "$user" , "$pass"))
or die ("Can't connect to MySQL");
$db = ((bool)mysqli_query( $connection, "USE " . $dbase)) or die ("Can't select database.");
?>
I've taken the liberty of rebuilding a bit on how you fetch your values, this should be a bit more easier to read and (in my opinion) a better structure. Also, you can specify the database in your connection, like this (just makes for easier reading, up to you really).
$connection = mysqli_connect($hostname, $user, $pass, $dbase);
if (!$connection) {
echo "An error occurred connecting to the database.";
exit;
}
Below is how your query could look. This will loop through all the results, and put them into the variables, only if we actually have a result.
<?php
include "connect.php"; // Connect to RDS
$query = "SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
if (!$result = mysqli_query($connection, $query)) {
// An error occured, do something
// This means no results could be fetched
}
$num = mysqli_num_rows($result);
if (!$result) { // This means that we only fetch if we have a result
while($row = mysqli_fetch_assoc($result)) {
// Fetching all the rows
$username = $row['username'];
$oldurl = $row['oldurl'];
$homedata = $row['homedata '];
$clientemail = $row['clientemail'];
$general_info = $row['general_info'];
$company_name = $row['company_name'];
$company_hours = $row['company_hours'];
$company_phone = $row['company_phone'];
$company_support_email = $row['company_support_email'];
$beyondscope = $row['beyondscope'];
}
}
?>
JFYI.
There is absolutely no point in converting your inspection app to MySQLi the way it offered in the other answer.
The only point in such a conversion is to make your queries safe while with such a direct conversion it remained congenially vulnerable. So, you might saved yourself a lot of trouble by leaving this code alone, with exactly the same outcome.
Proper way is described in this answer, but you will have to find another volunteer to write a code for you.
So, I have a form that posts to my php file using ajax, and succeeds. But the following query doesn't insert anything. Can someone help me understand what I'm doing wrong?
My php file:
<?php
include 'connect.php' ;
$type = mysql_real_escape_string($_POST['type']);
$title = mysql_real_escape_string($_POST['title']);
$content = mysql_real_escape_string($_POST['content']);
if ($type == 'Just Text') {
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('".$title."', '".$type."', 0, '".$content."')")or die("MySQL Error: " . mysql_error());
}
?>
My connect.php:
<?php
$dbhost = "localhost";
$dbname = "example";
$dbuser = "test";
$dbpass = "test";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
If you aren't receiving any errors and the INSERT just doesn't happen, it is most likely because the if statement fails to be true. Verify that $type actually matches Just Text.
You should also be inserting values using prepared statements, and use PDO or MySQLi - this article will help you decide which.
first, echo "something" after the if statement and recall the data with your ajax post. you can find out if your if statement is working, then try formatting your variables like so
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('$title', '$type', 0, '$content')")or die("MySQL Error: " . mysql_error());
I just want to throw in an official vote/recommendation in favor of switching to a parameterized SQL statement, too. In spite of the use of mysql_real_escape_string, schlepping a SQL statement together via string concatenation is neither necessary nor a good idea. Honestly, I find a prepared statement much, much easier to read than the typical string-concatenation exercise, as well:
$stmt = $dbh->prepare("SELECT * FROM users WHERE USERNAME = ? AND PASSWORD = ?");
$stmt->execute(array($username, $password));
Alright, it was a stupid mistake on my side. There were columns I didn't include and they were not being assigned a value. Thanks everyone for helping out.
CODE UPDATED, STILL NOT WORKING.
I know I´m apparently using mysql function which will be outdated. But for now all I want is for this code to work. I want to know what I´m doing wrong:(
I´m very new to php and databases... I have been struggling to get simple html form data to go into the database table. And I just can´t get it to work:( Can anyone help and see what is wrong with my code? I´ve just done a simple table in the database with the fields ID, FIRSTNAME and SURNAME.
Here is the code:
<?php
//connect to database
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_db = 'test';
if (!mysql_connect ($mysql_host, $mysql_user, $mysql_pass)||!mysql_select_db ($mysql_db) ) {
die(mysql_error());
}
// Code
if (isset($_POST['firstname'])&&
isset($_POST['surname'])) {
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
if (!empty($username)&&!empty($password)) {
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
/*$query = "INSERT INTO `test`.`test_tabell` VALUES (``, `.$firstname.`, `.$surname.`)"; */
$query_run = mysql_query($query);
if (!$query_run) echo mysql_error();
}
}
?>
<form action="add.php" method="POST">
Firstname:<br> <input type="text" name="firstname" value="<?php if (isset($firstname)) { echo $firstname; } ?>"><br><br>
Surname:<br> <input type="text" name="surname" value="<?php if (isset($surname)) { echo $surname; } ?>"><br><br>
<input type="submit" value="Submit">
</form>
Thank you!
Don't use mysql specific syntax, It's outdated and it begins to be annoying when you need to do some high level stuff, and you can't switch to sqlite or postgresql.
I recommend using PDO, you can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables (I think you forgot to define the name of the database);
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$GLOBALS['db'] = connectToDataBase($host , $databaseName, $user, $pass);
Now you have an instance of a PDO database donnection.
One thing I want to point out is that you're vonurable to sql injections, you want to use prepared statements in your query, like:
$query = "INSERT INTO test(first_name, sur_name) VALUES (:firstname, :surname);";
Where we will execute two variables $firstName and $surName on the query, making them replace the values of :firstName and :surName, let me show you by first creating a simple insertion function:
function insertFunction($db, $query, $firstName, $surName)
{
$statement = $db->prepare($query);
return $statement->execute(array(":firstName" => $firstName, ":surName" => $surName));
}
So It's easy for you to do something like
$firstName = 'Smith';
$surName = 'John';
$db = $GLOBALS['db'];
$success = insertFunction($db, $query, $firstName, $surName);
Now you can check if it was successful or not, by checking whether $success is true or false.
If you want to see more advanced use of PDO (multiple rows etc) then you can check out one of my comments here: Javascript function as php?
(Not the top comment).
I hope this helps. Please comment if anything is odd.
Hard to tell without seeing your schema but try this:
$query = "INSERT INTO `test`.`test_tabell` VALUES ('', '$firstname', '$surname')";
$query_run = mysql_query($query);
You're using backticks instead of apostrophes. Also, you're trying to execute a query before defining what the query is.
Your insert query is wrong and also open to SQL injections. Here's how it should be:
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
Notice the changing of all backticks to apostrophe.
Also, you're trying to execute the query before defining it.
EDIT
As per your information related to table definition, you can skip the id field from your table. The INSERT query will become:
$query = "INSERT INTO `test`.`test_tabell` (`FIRSTNAME`, `SURNAME`)
VALUES ('" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
$query_run = mysql_query( $query );
As posted in the comments, you REALLY SHOULD NOT use/learn/practice using any function that starts with "mysql_" since it will NOT work as soon as PHP is updated. These functions are on their way out. Best of luck with learning to use PHP and SQL databases - just make sure you're learning something that will be useful in the future. Make sure to read up on Object Oriented Programming (OOP) in relation to PHP and both the PDO and mysqli_* functions.
Almost identical to a previous question however I am now trying to use mySQLi to record some form data.
After I submit, the data does not post to the table. I've been reading through to the mySQLi documentation and some different videos but I can't figure it out.
Thanks in advance!
<?php
include('config.php');
if (
isset($_POST['store_id']) &&
isset($_POST['item_title']) &&
isset($_POST['date']) &&
isset($_POST['price'])
)
{
$store = get_post('store_id');
$item = get_post('item_title');
$date = get_post('date');
$price = get_post('price');
$query = "INSERT INTO ebay_data VALUES('".$store."', '".$item."', '".$date."', '".$price."')";
$input = $db_mysqli->query($query);
}
?>
You want to make sure your config is actually connecting of course. I typically just go to do it on one page if I get stuck, either way try:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', my_databasename);
/* check connection */
if (mysqli_connect_errno()) {
printf('Connect failed: %s\n', mysqli_connect_error());
exit();
}
$query = 'INSERT INTO ebay_data VALUES($store, $item, $date, $price)';
$mysqli->query($query);
printf ('New Record has id %d.\n', $mysqli->insert_id);
/* close connection */
$mysqli->close();
See if you get anything out on the page. Also should double check your post values are not empty. I have also ran into weird problems where setting the post to a var messed up sql queries, maybe try:
if (isset($_POST['store_id']) && isset($_POST['item_title']) && isset($_POST['date']) && isset($_POST['price']))
{
$query = "INSERT INTO ebay_data VALUES($_POST['store_id'], $_POST['item_title'], $_POST['date'], $_POST['price'])";
...
You also 100% need to check those post values, keeping your database and users safe. Prepared statements is a start. You do need a lot more than that though to keep it safe...
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php