everything functions on the side of data validation and error gathering and such, I get a problem specifically where $r is being executed. I always get the echo error. I've used this same bit of code before, but for some reason isn't working. Just need a second look of eyes at it perhaps.
if (empty($errors)){
$q = "INSERT INTO testTable (test1, test2) VALUES ('Test', 'Test')";
$r = #mysqli_query($dbc, $q);
if($r){
echo 'Complete!';
}
else{
echo 'error';
}
mysqli_close($dbc);
include('footer.html');
exit();
I can enter the statement manually in MySQL and it will add it to the table, so I don't think its a syntax error there, I am just a little tired at this point.
"I'm getting a lot of warnings saying that parameter 1 of mysqli_xxx must be mysqli. So does that mean that my $dbc variable isn't working properly?"
The reason for that may very well be because your DB connection method is probably based on mysql_connect() or PDO to connect with.
Something you haven't posted in your question.
Those different MySQL APIs do not intermix with each other.
mysql_ + mysqli_ or PDO = no love. mysqli_ + PDO, same thing.
Refer to both manuals:
MySQLi: http://php.net/manual/en/function.mysqli-connect.php
PDO: http://php.net/manual/en/pdo.connections.php
and use only "one" MySQL API, from beginning to end and not a "mix of".
You should also remove the # symbol(s) from your code. Those are error suppressors and won't help you when debugging code.
So your connection for MySQLi_ would look something like this:
$dbc = mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($dbc));
Unlike mysql_:
$dbc = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$dbc) {
die('Could not connect: ' . mysql_error());
}
Related
I want to make a simple announcements system where you just type announcements in a box and it can be viewed by others. I get this error when I submit the form:
Edit:
Thanks, the php_announce.php now works, it does everything it's supposed to do, this is the new code :
<?php
// MySQL
$servername = "localhost";
$username = "testuser";
$password = "testpass";
$dbname = "testbase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Content
$content = $conn->real_escape_string($_POST['content']);
$query="INSERT INTO announcements (content) VALUES ('$content')";
$conn->query($query)
?>
Edit: Thanks for the help I fixed the code like this:
after creating connection it does this:
$result=$conn->query("SELECT * FROM announcements");
#print_r($result);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['content']. " <br><br> ". "<b>Posted by: You</b>";
echo "<hr width=100%>";
}
In the first case, you need to provide a list of columns that correspond to the values you're trying to insert. e.g:
$query="INSERT INTO announcements (content) VALUES ('$content')";
Replace content with the name of the column in your table.
For the second one, the error message doesn't appear to correspond with the code you posted, but I'm guessing you forgot a semicolon on the preceding statement. Additionally, there's a missing ; in your last echo statement, although I'm not sure if that's what's causing the specific message you posted. Please repost the latest code from announce_out.php and I'll try to help.
There are some other issues with this approach in general. You're mixing mysqli and the older mysql, which is going to cause you additional errors. Instead of calling mysql_query(), you should be using $conn->query($query) so that you're actually using the connection you are establishing with new mysqli(). Additionally, to prevent injection attacks, you should escape your $content variable in this way:
$content = $conn->real_escape_string($_POST['content']);
This is a pretty basic way to escape strings and there are better methods like prepared statements that mysqli provides. I recommend checking out the page in the PHP manual: http://php.net/manual/en/mysqli.quickstart.php
The immediate answer to your problem is:
You need to escape the content and let the function quote it for you.
$content= mysql_real_escape_string($_POST['content'], $conn);
$query="INSERT INTO announcements VALUES ($content)";
and you need a missing semicolon at the end of the echo statement.
echo $row['content']. " <br><br> ". "<b>Posted by: You</b>";
The long term answer is you should really look into a database abstraction layers which help you avoid incredibly dangerous errors you're likely to make (like incorrectly escaping content). See php manual for some basic ones: http://php.net/manual/en/refs.database.abstract.php
But I also highly recommend using a higher level framework like Doctrine http://www.doctrine-project.org/.
UPDATED VERSION
<?php
$link = mysqli_connect("localhost", "root", "root", "metadata");
mysqli_set_charset($link, "utf8");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// my form located in index.php posts the data here.
$add_movie_original_name = $_POST['movie_original_name'];
$add_movie_tr_name = $_POST['movie_tr_name'];
$add_movie_year = $_POST['movie_year'];
$sql = "INSERT INTO movie(movie_original_name,movie_tr_name,movie_year) VALUES('$add_movie_original_name','$add_movie_tr_name','$add_movie_year')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
I can't add records if there is an apostrophe in it. For instance, Uncle Sam's can't be added.
Here is the error I get. I tried to add a movie named Movie's Name.
ERROR: Could not able to execute INSERT INTO movie(movie_original_name,movie_tr_name,movie_year) VALUES('Movie's Name','','2014'). You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Name','','2014')' at line 1
(I deleted my comments, so line number will be different)
I think I should use a trick to escape the characters, but couldn't find out how.
You nee to be preparing your statements so that you aren't vulnerable to an SQL Injection attack. To do this, you should be using mysqli prepared statements. Your current code would look like this as a prepared statement
$mysqli = new Mysqli("localhost", "root", "root", "metadata");
$statement = $mysqli->prepare("INSERT INTO movie(movie_original_name,movie_tr_name,movie_year) VALUES('?','?','?')");
$statement->bind_param('sss', $add_movie_original_name, $add_movie_tr_name, add_movie_year);
$statement->execute();
Notice how in the actual SQL, I've replaced your variables with ?'s, this let's them be bound later on. In my bind_param method, the first parameter is how many variables you're binding, and what data types they are. There's one character for each variable, and they're all strings, so that character is "s". If you wanted to bind integers and strings, you would use
$statement->bind_param('sis', $string1, $int1, $string2);
Notice how the order of "sis" matches the order of what's passed it, string then integer then string again. According to the PHP Manual, there are four different types you can pass in, each with their own characters
s for string
i for integer
d for double
b for blob
So that's a short explanation of bound params. The problem you're having comes from the fact that your variables aren't escaped or bound, leaving them open to injection. This will fix your problem and make your code a little bit more secure.
Note: As pointed out by #bcintegrity, this isn't the be all end all for security. You're going to want to look into using htmlspecialchars() when echoing out your data that's been entered in by users in order to stop XSS (Cross Site Scripts) which can be very dangerous to not patch up.
Make it a priority to use prepared statements. Prepared statements simply send the query separate from the values, so the db knows the values are not to be run as code. Prepared statements escape the values automatically :)
Here is an example:
$sqli = #mysqli_connect("localhost", "root", "root","metadata");
if (!$sqli) {die("Can not connect to the database: " . mysqli_connect_error());}
$result = "INSERT INTO `movie`(movie_original_name,movie_tr_name,movie_year) VALUES (?,?,?)";
$stmt = mysqli_prepare($sqli, $result);
mysqli_stmt_bind_param($stmt,"sss",$_POST['movie_original_name'],$_POST['movie_tr_name'],$_POST['movie_year']);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
Be sure to use htmlspecialchars() if echoing values onto the page to protect from XSS:
$original_name_onscreen = htmlspecialchars($_POST['movie_original_name']);
$tr_name_onscreen = htmlspecialchars($_POST['movie_tr_name']);
$year_onscreen = htmlspecialchars($_POST['movie_year']);
Note: #Gareth Parker's example is object oriented style, similar to PDO, while mine is procedural style, similar to MySQL. Both are acceptable.
I tried inserting a row in a table using a php and HTML file in dreamweaver however it is not showing up when I refresh phpMyAdmin page?
PHP
<?php
$username="root";
$database="conception";
mysql_connect("127.0.0.1" ,$username);
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO order VALUES ('','Shirt','M','black','that photo','L','none','UL','none','Sharpiee','#E0E0E0','BIU','Lobster','bottom','L')";
mysql_query($query);
mysql_close();
?>
I also used "localhost" instead of 127.0.0.1 but that did not work aswell. When i press the button in my form first it showed mysql_connect error but then i removed the password as a perimeter and onCLick it moves to a blank page.
First of all don't use mysql extension any more, it's deprecated of PHP 5.5 and will be removed in future, so use mysqli or PDO extension instead. Second mysql_connect() function should have 3 parameters. Check it here.
ORDER is a MySQL reserved keyword. That word is used for doing ORDER BY, an optimization method.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Either wrap it in backticks or use another word for it (rename your column to "orders") which is OK.
$query = "INSERT INTO `order` VALUES ...
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
which would have signaled the error.
Also add or die(mysql_error()) to mysql_query().
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
Look up DB connection method for mysql_ functions:
http://php.net/manual/en/function.mysql-connect.php
From example #1
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
From mysql_select_db - DB selection.
From example #1
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
I have been working for days now and I am at a dead end. After talking with GoDaddy support I am positive that I have the correct hostname, username/password when I run the script but it still cannot get past die().
Ultimately I am attempting to pull a single question from a database. I have combed this website but nothing i found seems to answer my question. Please help.
<?php
$hostname='localhost';
$username='username';
$password='password';
$dbname='qod';
$usertable='Questions';
$userfield='question';
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to access the Question of the Day! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = 'SELECT $.userfield FROM $.usertable ORDER BY RAND() LIMIT 1';
$result = mysql_query($query);
if($result){
while($row = mysql_fetch_array($result)){
$name = $row[$yourfield];
echo "Name: ".$name;}
}
?>
You are using dots for your SELECT variables where there shouldn't be any.
SELECT $.userfield FROM $.usertable, then calling them with:
$usertable='Questions';
$userfield='question';
Remove them from your SELECT and use proper error reporting techniques such as :
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of code
and
or die('Could not connect: ' . mysql_error());
also a dollar sign in [$yourfield] for your column name; remove it also.
You should be using quotes: I.e.: ['yourfield'] - yourfield being the column name in your table that you wish to show.
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Use mysqli_* with prepared statements, or PDO with prepared statements.
I have used tutorials, examples and looked at numerous other questions about my problem and I still can't get it to work, I am relatively new to PHP and do not have any understanding of PDO. I have changed my code to mysqli rather than mysql to get rid of the depreciated code my university gave me but they have been less than helpful during this situation.
If anyone could shed some light onto this issue for me I would be very grateful.
Below are my code samples:
<?php /*connect to the db */
$link=mysqli_connect("dbhost","user","pass");
mysqli_select_db("db",$link);
/*checking connection*/
if ($link->connect_errno)
throw new exception(sprintf("Could not connect: %s", $link->connect_error));
session_start();
$insert_query="
INSERT INTO testone_tbl (age,hours,flexibility,fastpaced,retailexp,
workedus,conviction,permit,education)
VALUES ('$age','$hours','$flexibility','$fastpaced','$retailexp','$workedus',
'$conviction','$permit','$education');
INSERT INTO testtwo_tbl
(contribute,insales,initiative,success,alternatives,targets,
newthings,custfeed,incdevelop,standards,confident,stretch,
opportunities,polite,ideas,deadline,supported,duties)
VALUES ('$contribute','$insales','$initiative',
'$success','$alternatives','$targets','$newthings',
'$custfeed','$incdevelop','$standards','$confident','$stretch',
'$opportunities','$polite','$ideas','$deadline','$supported','$duties')";
/*execute multi_query*/
mysqli_multi_query ($link, $insert_query);/*error1*/
/*close connection*/
if(!$link>connect_errno) $link->close(); /*error2*/
?>
The data is both from the form this is written in (the last form) and sessions from the previous forms. However I am also getting this error: Warning: mysqli_multi_query() expects parameter 1 to be mysqli and Warning: mysqli_close() expects parameter 1 to be mysqliand I have been stuck on this the past few days! Thank you in advance.
You should first check with your web host if they have enabled multi-SQL-queries.
Some web hosts only allow single-SQL queries to help prevent against injection attacks.
If, however, you want to multi-insert to the same table, you could do it like this:
INSERT INTO tbl_name (col1, col2)
VALUES ('?', '?'),
('?', '?'),
('?', '?'); # inserts 3 records to the same table in one query
Also, if you do have PDO available to you, use it!
With a PDO object, your queries will be safer by using prepared statements. Example:
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$data = array($col1, $col2, $col3);
$sql = "INSERT INTO tbl_name (col1, col2, col3) VALUES ('?', '?', '?');";
$query = $db->prepare($sql); # prepares the sql statement
$query->execute($data); #binds the array of data to the ?
#question mark parameters, and executes.
If you create a database abstraction layer, you could change the database connection mode without having to rewrite your code which executes your queries.
Also, do you have a reason not to loop and query? Example:
$sql_array = array("INSERT INTO tbl_one(col1) VALUES '?';",
"INSERT INTO tbl_two(col3) VALUES '?';");
function performAll($sql_array) {
# execute all of the queries
}
It has occured to me that you may be using some function to access your database connection. Now that is not a problem, unless you actually try to access the database connection from within a function (in case you have not told us). Example:
$db = new PDO("...", $user, $pass);
$query = $db->prepare($sql); # works fine
function executeQuery($sql) {
$query = $db->prepare($sql); # error: $db is not defined
# within the scope of this function
...
}
To get around this, use the global keyword in PHP. Example:
$db = new PDO("...", $user, $pass);
function executeQuery($sql) {
global $db; # use $db in the global scope
$query = $db->prepare($sql); # works fine
...
}
From the warnings it is clear that $link is not a mysqli object. Either you did not connect, or at some point you reassigned $link to something else.
You also need to check your connection immediately after your connect. An intermediate action on the link (in this case, mysqli_select_db) will clear any errors that were set.
You should also not mix-and-match object-oriented and procedural style interfaces for mysqli. The object-oriented style is much clearer, but if it's too difficult to change the existing code then stick to the procedural style.
Connect like this instead:
$link = mysqli_connect("dbhost","user","pass", "db"); // no need for an extra db select
if (mysqli_connect_errno()) {
throw new Exception("Could not connect: ".mysqli_connect_error());
}
Also, I hope this isn't your real code, because it is wide open to mysql injection attacks. Consider dropping the use of multi-queries entirely and using prepared statements with placeholders.