I am writing a script that uses data from the user to create a page and create a database entry for the created page. Unfortunately, despite the fact that the query I am using was generated by phpmyadmin, the insert does not succeed.
I have attempted using both mysql and mysqli for all of the function calls(not at the same time obviously) but have received the same result regardless.
While I would love to understand why the insert is failing the more pressing issue is the fact that no error is being produced.
The error conditional is being entered but both mysql_error() and mysqli_error() end up empty.
This is the segment of code where the error occurs:
$result = mysqli_query($pvcon,"'INSERT INTO content
(content.post_type_id,
content.content_title,
content.content_description,
content.content_link,
content.user_id,
content.content_image_path,
content.date_posted)
values (\'".$post_type."\',
\'".$title."\',
\'".$description."\',
\'".$content_link."\',
\'".$user_id."\',
\'".urlencode($article_image)."\',
now())'");
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysqli_error();
exit;
}
I have found multiple questions that are similar to mine but none of those solutions have worked for me which leads me to believe that there is some simple step that I am overlooking.
$result = mysqli_query($pvcon,"'INSERT INTO content
^---
..... snip....
now())'");
^----
your entire query is wrong - you've enclosed it in '-quotes, making the ENTIRE query a monolithic string. And your error call never works, because you've forgotten to include the link identifier in the call:
echo 'MySQL Error: ' . mysqli_error($pvcon);
^^^^^^--missing.
Plus, given the variable names you're using, you're probably ALSO vulnerable to SQL injection attacks, so enjoy having your server pwn3d on top of all this.
Related
I'm trying to insert into my database and have been frustratingly not been able to get my statement(s) to work. I'm using PHP's MySQL Improved (mysqli) procedural interface. It might be worth noting that I'm using the c9.io IDE (pre-AWS) and everything including the server that my application is running on is through c9.
What I've noticed is that the statements have been working randomly. Initially, I was making very subtle changes to my INSERT statements until it worked, but after the working trial, it would fail again. So, eventually I started hitting the refresh button (same inputs, no modifications to my code) repeatedly until I hit a success.
In terms of code:
$sql = "INSERT INTO `users` (`email`,`password`) VALUES ('example#mail.com','1234')";
$result = mysqli_query($connection,$sql);
gives
$result = false
very consistently, but every random nth trial
$result = true
(same inputs, no change to my code).
I do not believe it is an error with my SQL syntax considering the random successes, nor do I believe it is an error with my connection. All of my SELECT statements have been working fine.
Thus, I have a hunch that for some reason it may be an issue with c9? If you have ever had a similar issue with any of MySQL, SQL, PHP, or c9, please help!
You Should try this
<?php
if (!mysqli_query($connection,"INSERT INTO Persons (FirstName) VALUES ('Glenn')"))
{
echo("Error description: " . mysqli_error($connection));
}
?>
Use myqli_error() which will give you a error message which should help clarify the issue with your code
i am trying to get data from input box and pass it to the database to show appropriate records and results but need help not able to get result
<html>
<body>
</body>
</html>
<?php>
$prod_name = $_POST["name_of_the_product"];
echo [$prod_name];
$db_host = "localhost";
$db_username = "acwj_price";
$db_pass = "";
$db_name = "acwj_price";
mysql_connect("$db_host","$db_username","$db_pass") or die ("Please Try Again");
mysql_select_db("wikiacwj_price") or die ("no data");
$sql = mysql_query("SELECT * FROM price_comparsion where product_name="prod_name"");
//write the results
while ($row = mysql_fetch_array($sql)) {
echo $row['product_name'];}
?>
</body>
</html>
Warning: CARGO CULT PROGRAMMING DETECTED!. You've got syntax errors galore, you've got SQL injection holes, you've got useless error handling, blah blah blah. In other words, the code is a mess.
1) echo [$prod_name]; what are the [] for here? This is a flat out syntax error
2) mysql_connect("$db_host" etc... - why the "" around variables? You'r creating a new empty string, embedding another string inside that - a total waste of cpu cycles.
3) or die ("Please Try Again"); - of what use is it to tell your site's user to try again? If your code can't log into mysql, how is the user supposed to fix this? Hammering on reload won't make an invalid mysql login magically start working again. If you're the only user of the code, at least have a useful error message output, explaining why the script is dying, e.g. or die(mysql_error()).
4) ... where product_name="prod_name""). You've got another horrendous syntax error here - you cannot embed quotes within a string that is built with the same type of quotes you're trying to embed.
4a) Should that be ... product_name='$prod_name'", perhaps, so you're actually embedding the form value that was passed in?
4b) $prod_name is now your SQL injection source, and you should have AT MINIMUIM $prod_name = mysql_real_escape_string($_POST['name_of_product']), and have it somewhere AFTER you connect to the DB, since m_r_e_s() only works when you have an active DB connection.
We need more context to give you a solid answer, however reviewing your code I've found the following things that are causing problems:
echo [$prod_name]; is incorrect - should be echo $prod_name;
Also, the mysql_connect is incorrect - should be: mysql_connect($db_host,$db_username,$db_pass) or die ("Please Try Again");
(you should not have quotes around the variables)
And the sql statement is incorrect - should be:
$sql = mysql_query("SELECT * FROM price_comparsion where product_name='" . mysql_real_escape_string($prod_name) . "'");
(corrected the quoting, changed to pass in the variable, and added mysql_real_escape_string as minimum sql error prevention)
Note: This does NOT reflect best practices with SQL - there's all sorts of SQL Injection attack vulnerabilities in the original code - this code is only revised to work. If you will be writing code like this, you should should read about SQL Injection prevention. There's plenty of good information on StackOverflow - here's just one example: SQL Injection, Quotes and PHP
[UPDATED] with new code "sql_real_escape_string()"
[UPDATED] if anyone wants to look at the site its at Test site
[UPDATED] with the while code showing any results via echo
Hello All,
I have looked at many posts on this matter, but simply cannot understand why the following code doesn't work:
$username = $_POST['username'];
// get the record of the user, by looking up username in the database.
$query = sprintf("SELECT UserName, Password FROM userlogin WHERE UserName='%s'", mysql_real_escape_string($username));
$result = mysqli_query($dbc, $query) or
die ("Error Querying Database for: " . $query .
"<br />Error Details: " . mysql_error() . "<br/>" . $result);
while ($row = mysqli_fetch_assoc($result))
{
Echo($row['UserName']);
}
The Code seems to be correct... the database is working perfectly (for input purposes) and the connection is a shared connection applied with require_once('databaseconnection.php'); that is working for the registration side of things.
like normal I'm sure this is something simple that I have overlooked but cannot for the life of me see it!
I do not get any error messages from the myssql_error() its simply blank.
any help would be much appreciated.
Regards
Check the username you try to query as it might be empty. Do you really use a post-request to run that script? How do you verify that it does not work? What do you do with $data after the query?
If just nothing seems to happen it is likely your query did not match any record. Check for whitespace and case of the username you are looking for.
Mind those warnings:
Use a prepared statement or at least sql-escape any user-input before using it in sql.
Don't use die in serious code only for debugging.
The $data will contain a result object. You need to iterate over it using something like mysqli_fetch_assoc($data).
Also, you can interpolate variables directly into double quoted strings - i.e. UserName='".$username."'" could be written more cleanly as UserName='$username' rather than breaking out of the string.
Also, please sanitize your input - all input is evil - using mysqli_real_escape_string() function. You've got a SQL injection exploit waiting to happen here.
Bear in mind that it's a very good idea to validate all data to be inserted into a database.
Very often you have problems with query itself, not implementation. Try it in phpMyAdmin first and see if there are any problems.
Check server logs.
BY THE WAY: Never put variables from POST to query! That's definitely a SQL injection'
You might have some issue with the query.
Have you Tried to echo the $query and run that directly with mysql client or workbench?
This piece of code seems ok. That is, if $dbc contains an actual database connection. But the choice of naming that variable $data while the function actually returns a result object or a boolean, indicates that you may process the data wrong.
If that is not the problem, we'll definately have to see more code.
Try printing $data variable instead of printing only query. Check, whether you are able to get any error messages. If you could see any data then you should use mysql fetch function to iterate things. Try it.
$result=mysql_query("SELECT * FROM playerlocations WHERE player<>'0'");
$returntext="";
while($row=mysql_fetch_array($result))
{
if($returntext!=""){$returntext.="&";}
$returntext.=$row['player']."#".$row['locations'];
}
the error message claims that $result isn't a valid result set. I tested it in phpmyadmin, and it worked. I don't know why it won't work here, please help.
It says it isn't a valid result set. That doesn't necessarily mean it isn't a valid query. (Although != instead of <> would be nice.)
To figure out why it's not valid, output the result of calling mysql_error() after running the query:
echo mysql_error(); //most direct way to do this
It will tell you what MySQL reports as the error message.
One obvious thing to check: have you opened the connection (with mysql_connecst()) before running the query?
We have a function used within our PHP/MySQL application which returns basic configuration information, it contains a simple select query and looks like this:
public function getConfigurationValue($field)
{
$res = mysql_query("SELECT `cfg_value` FROM `ls_config` WHERE `cfg_name` = '".mysql_real_escape_string($field)."'");
$cfg = htmlspecialchars(mysql_result($res,0));
return $cfg;
}
This problem we are having is that occasionally, seemingly at random, this query throws a mysql error on mysql_result saying that "supplied argument is not a valid mysql result resource". In our debugging we have determined though that this is not because $field is not being passed. Essentially, for a reason we cannot determine a perfectly valid query fails and returns no results causing an empty result set and the subsequent error. If the error was due to the mysql connection failing the script would have died well before this. Also, this function may be called 50-100 times on some page loads but it only tends to fail once on each load.
Please let me know if you need any other information to work this out.
Thanks.
searching for php "supplied argument is not a valid mysql result resource" reveals that to get the actual error, you'd need to call mysql_error, and the error that you get is because the result of the query is FALSE - this value not being a valid mysql result resource.
i.e. in short you have something like:
$res = FALSE; # should contain the mysql result but does not, due to error.
$cfg = htmlspecialchars(mysql_result($res,0)); # the attempt to call mysql_result on invalid argument errors out.
So you'd want to use something like this:
$query = "SELECT * FROM cats WHERE id=$id";
$qr1 = mysql_query ($query)
or die ("Query failed: " . mysql_error() . " Actual query: " . $query);
You might want to give this a shot and see what the underlying error message says.
Given that the error is "MySQL server has gone away", There can be multitude of reasons for it - this article would be a good start to investigate. Searching suggests also some php-related and stack-specific bugs, so it looks like you might need to debug it with a closer attention.
Maybe try to duplicate the setup on another box and then start experimenting with the versions/settings, and see if any of the already reported scenarios match your case. Unfortunately, seems there's no single simple answer to this.