Following this syntax:
Here is generic SQL syntax of UPDATE command to modify data into MySQL table −
UPDATE table_name SET field1 = new-value1, field2 = new-value2 [WHERE Clause]
from https://www.tutorialspoint.com/mysqli/mysqli_update_query.htm
I made this:
$query = mysqli_query($MYSQL_CONNECT, "UPDATE forum_topics SET player_userid = ".$player_userid.", titulo = ".$titulo.", msg = ".$msg.", data = ".$data." WHERE UserID=".$inTopic."");
mysqli_query($MYSQL_CONNECT,$query);
But on line:
mysqli_query($MYSQL_CONNECT,$query);
Is showing:
mysqli_query(): Empty query in /var/www/html/ucp/php_func/edit_topic.php on line 30
The main problem is that you're trying to execute your query twice. And the second attempt is invalid because, where it expects a string query, you're either passing it a result object or a boolean (if the first query failed).
Just execute your query once:
$query = mysqli_query($MYSQL_CONNECT, "...");
Then the value in $query will be the result.
Additionally, you have the problem that your code is open to SQL injection and you're not checking for errors. If mysqli_query() returns false you'd need to examine what went wrong by using mysqli_error($MYSQL_CONNECT), which returns the error as a string.
For the SQL injection problem, what you should be doing is treating values as values (query parameters) instead of as executable code (by concatenating them directly into the query). This is a great place to learn more about that. Note that SQL injection is not just a security concern but is also a very common source of errors and bugs. Since you're currently having exactly that problem, it's worth correcting.
You should wrap your variables in single quotes, try:
$query = mysqli_query($MYSQL_CONNECT, "UPDATE forum_topics SET player_userid = '".$player_userid."', titulo = '".$titulo."', msg = '".$msg."', data = '".$data."' WHERE UserID='".$inTopic."'");
Related
I want to get some data from a Sphinx server and pass it to MySQL to execute some queries. I'm new to PHP so probably I'm missing something here. I've looked for similar questions but can't find anything so maybe you can help me.
The error is in the first while. I'm pretty sure it's due to the $rown variable but don't know the reason. (I've verified that I can retrieve data from the connections so it is passing the data where the error lies - could be the sql syntax of the query but that seems fine).
Edited the code thanks to the comments below, now I get the error: Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\test3.php on line 20. This is because the query failed, I still suspect it is because $rown.
$sphinxcon = mysqli_connect...
$mysqlcon = mysqli_connect...
$query = "SELECT names FROM iproducts LIMIT 0,1000";
$raw_results= mysqli_query($sphinxcon, $query);
//Until here works ok, now I want to pass $raw_results to MySQL
while ($row = mysqli_fetch_object($raw_results)) {
$rown = $row->names;
$mquery = "SELECT text FROM claims WHERE EXISTS ($rown) LIMIT 0,1000";
$mysqlresults = mysqli_query($mysqlcon, $mquery);
while ($final = mysqli_fetch_object($mysqlresults)) //this is line 20
{
printf ("%s<br />", $final->text);
}
}
Thanks :)
Well $row contains an object, so would have to use it as such, maybe
$rown = (string)$row->names;
... assuming you want the variable to contain the 'names' attribute you just SELECTed from Sphinx index.
As for the mysql EXISTS(), no idea what you really doing here, seems confused. How you structured it currently suggests that 'names' attribute in sphinx contains a complete SELECT query, that mysql could execute for the exists condition. That seems unlikely.
Guessing you meaning to more normal query something like
$mquery = "SELECT text FROM claims WHERE text LIKE '%$rown%' LIMIT 0,1000";
But that is subject to SQL injection, particully if names might contain single quotes. SO should escape it. Perhaps
$rown = mysqli_real_escape_string($mysqlcon, $row->names);
But might be worth reading up on prepared queries.
btw, the 'Error' you getting, is because you creating an invalid query and not dealing with it. So $mysqlresults is FALSE.
$mysqlresults = mysqli_query($mysqlcon, $mquery) or die("Mysql Error: ".mysqli_error($link)."\n");
When I add AND operator in mysql_query() function, it stops working and anything after that stops working!
For Example:
When i wrote this:
$query1 = mysql_query("SELECT * FROM chat1 where friendname = '$_POST[fname]' ");
$row= mysql_fetch_array($query1) or die(mysql_error());
echo "$row[message]";
The above query runs successfully !
But when i do this :
$query1 = mysql_query("SELECT * FROM chat1 where friendname = '$_POST[fname]' AND username = '$_POST[uname]' ");
$row= mysql_fetch_array($query1) or die(mysql_error());
echo "$row[message]";
I get Null output!
I think the "AND" operator is not working!!!
please help me with this!!
Have a look at my complete code and Database Snapshot!
Click here
If it is returning NULL then probably the record doesn't exists. Try to output this query on the screen and post the raw query here.
Maybe your search needs a LIKE instead of a =
Likely, the row(s) you are looking for do not exist.
The AND is a boolean operator that requires that both expressions have to evaluate to true. In the context of your query, that means for a row to be returned, both of the conditions have to be true on that single row.
I suspect that you may want an OR those two conditions. Did you want to return only rows that meet both criteria, or did you want any rows that have fname with a certain value, along with any rows that have uname of a specific value? If the first query is returning rows, then replacing AND with OR should return you some rows.
For debugging this type of problem, generate the SQL text into a variable, and then echo or var_dump the SQL text, before you send it to the database.
e.g.
$sql = "SELECT * FROM chat1 where friendname = '"
. mysql_real_escape_string($_POST['fname'])
."' ";
echo "SQL=" . $sql ; # for debugging
Take the text of SQL statement that's emitted to another client, to test the SQL statement, to figure out if the SQL statement is actually returning the resultset you expect it to return.
(In your code, reference the $sql in the function that prepares/executes the SQL statement.)
Follow this pattern for all dynamically generated SQL text: generate the SQL text into a variable. For debugging, echo or var_dump or otherwise emit or log the contents of the variable. Take the SQL text to another client and test it.
Dumping code that isn't working on to StackOverflow is not the most efficient way to debug your program. Narrow down where the problem is.
How to debug small programs http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
NOTES
You probably want to verify that $_POST['fname']) contains a value.
It's valid (SQL-wise) for a SELECT statement to return zero rows, if there are no rows that satisfy the predicates.
Potentially unsafe values must be properly escaped if you include them in the text of a SQL statement. (A better pattern is to use prepared statements with bind placeholders, available in the (supported) mysqli and PDO interfaces.
Also, use single quotes around fname.... e.g.
$_POST['fname']
^ ^
I've got a strange problem. There are 2 queries.
$sql = "SELECT `content_auftrag_id`
FROM `content`
WHERE `content_id` = '".$content_id."' LIMIT 1";
$ergebnis = $db->prepare( $sql );
$ergebnis->execute();
$ergebnis->bind_result( $content_auftrag_vorhanden );
$content_auftrag_id = "test";
$sql = "UPDATE `content` SET `content_auftrag_id` = '".$content_auftrag_id."'
WHERE `content_id` = '".$content_id."'";
$ergebnis2 = $db->prepare( $sql );
$ergebnis2->execute();
When I use them both, then an error occurs for the second one. If I only run the the second, then it works fine. How can it be that both together cause an error?
All variables are there and correct.
Thanks!
Okay, I think you didn't quite got the idea behind PreparedStatements. You shouldn't directly insert the parameters in your SQL-String, but use ?-placeholders and bind them in the Query using the bind_param()-method.
Your error seams to appear here:
$ergebnis2 = $db->prepare( $sql );
This function returns false if it wasn't successful. You should check if the value of ergebnis2 is not false.
Also, you should use the error-method to see the last appeared MySQL-Error.
You can only work on one prepared query at a time, so to speak. See Mysqli::execute() method:
"When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries."
You can also use the store_result() method to remove this block as well to perform the next query.
Also, take heed from those who warn you about abusing prepared statements like your example. Though it works without error if you don't actually have any parameters to bind to, it basically throws sql injection prevention out the window.
If $ergebnis2 is 'not an object', then I guess it must be false. Which means the prepare() call failed for whatever reason.
What does $db->error return after you have called the 2nd prepare?
Always check your return values, its basic debugging
I've got the following code:
<?php
if(!empty($error_msg))
print("$error_msg");
else
{
require_once("../include/db.php");
$link = mysql_connect($host,$user,$pass);
if (!$link)
print('Could not connect: ' . mysql_error());
else
{
$sql = "insert into languages values(NULL,'$_POST[language]','$_POST[country_code]');";
$res = mysql_query($sql);
print("$sql<br>\n");
print_r("RES: $res");
mysql_close($link);
}
}
?>
In one word: it does not work. mysql_query doesn't return anything. If I try the same
query within php_myadmin, it works. It does not insert anything either. Also tried it as
user root, nothing either. Never had this before. Using mysql 5.1 and PHP 5.2.
Any ideas?
mysql_query will return a boolean for INSERT queries. If you var_dump $res you should see a boolean value being printed. It will return TRUE for a successful query, or FALSE on error. In no cases it ever returns NULL.
In addition, never pass input data (e.g.: $_POST) directly to an SQL query. This is a recipe for SQL injection. Use mysql_real_escape_string on it first:
$language = mysql_real_escape_string($_POST['language']);
$sql = "INSERT INTO language SET language='$language'";
And don't forget to quote your array indices (e.g.: $_POST['language'] instead of $_POST[language]) to prevent E_NOTICE errors.
You need to specify a database so the system knows which database to run the query on...
http://php.net/manual/en/function.mysql-select-db.php
Without selecting a database, your data will not be inserted
mysql_query returns a boolean for INSERT queries. If used in string context, such as echo "$res", true will be displayed as 1 and false as an empty string. A query error has possibly occured. Use mysql_error() to find out why the query has failed.
$sql = "insert into languages values(NULL,'$_POST[language]','$_POST[country_code]');";
This is very bad practise, as a malicious user can send crafted messages to your server (see SQL Injection).
You should at least escape the input. Assuming your column names are named 'language' and 'country_code', this is a better replacement for the above code:
$sql = sprintf('INSERT INTO LANGUAGES (language, country_code) VALUES ("%s","%s")',
mysql_real_escape_string($_POST['language']),
mysql_real_escape_string($_POST['country_code'])
);
For a description of the mysql_real_escape_string function, see the PHP Manual. For beginners and experienced programmers, this is still the best resource for getting information about PHP functions.
Instead of using $_POST directly, I suggest using the filter_input() function instead. It's available as of PHP 5.2.
With an INSERT query, mysql_query returns true or false according as the query succeeded or not. Here it is most likely returning false. Change the line print_r("RES: $res"); to print_r("RES: ".(int)$res); and most likely you will see it print RES: 0.
The problem may be that MySQL expects a list of column names before the VALUES keyword.
Also, you appear to be inserting POST variables directly into SQL - you should read up on SQL injection to see why this is a bad idea.
--I retract the quote comment, but still not good to directly insert $_POST values.--
Second, I don't think i've seen print_r quite used like that, try just using an echo.
And mysql_query is only expected a boolean back on an INSERT, what are you expecting?
Now ive got this:
$language = mysql_real_escape_string($_POST['language']);
$country_code = mysql_real_escape_string($_POST['country_code']);
$sql = "insert into shared_content.languages (id,language,country_code) values(NULL,$language,$country_code);";
$res = mysql_query($sql);
print("$sql<br>\n");
var_dump($res);
print(mysql_error());
mysql_close($link);
And the output:
insert into shared_content.languages (id,language,country_code) values(NULL,NETHERLANDS,NL);
bool(false) Unknown column 'NETHERLANDS' in 'field list'
I have the below sql query that will update the the values from a form to the database
$sql=
"update leads set
category='$Category',
type='$stype',
contactName='$ContactName',
email='$Email',
phone='$Phone',
altphone='$PhoneAlt', mobile='$Mobile',
fax='$Fax',
address='$Address',
city='$City',
country='$Country',
DateEdited='$today',
printed='$Printed',
remarks='$Remarks'
where id='$id'";
$result=mysql_query($sql) or die(mysql_error());
echo '<h1>Successfully Updated!!.</h1>';
when i submit I dont get any errors and the success message is displayed but the database isnt updated . When i echo the $sql, all the values are set properly. and when i ech the $result i get the value 1.
can someone please tell me what am i doing wrong here??
Have you tried running the echo of $sql directly using some DB tool? It may provide a more informative error. Alternatively, if that works you may have an issue where the transaction isn't being committed. Often a connection is set to automatically commit transactions, but that may not be the case here. Try adding a commit.
And have you ever heard of SQL injection attacks?
If you have a query that is not giving the expected result or receiving an error, and the problem isn't obvious, you should generally take a look at the final query just before it's run. Try using this right before running the query:
echo $sql;
exit;
Viewing the actual query often makes it obvious what the problem is, especially when the query includes variables. If the problem still isn't obvious, you can paste the query as is into a query browser to get feedback directly from the database engine.
Interestingly, using parametrized queries, you won't get to see the parameter values, as the parameters get replaced by MySQL, not PHP, however, you'll still get to see the entire prepared query.
Also, you can see the number of affected rows from your UPDATE statement with the mysql_affected_rows() function. You could put this immediately after the query is run:
echo ("Updated records:", mysql_affected_rows());
Spaces are often forgotten when concatenating queries.
$sql = "SELECT * FROM ducks";
$sql .= "WHERE duck = 'goose'";
When echoing the above query, we see:
SELECT * FROM ducksWHERE duck <> 'goose'
I'm guessing that the WHERE clause in your UPDATE statement isn't matching an "id = '$id'".
Also, is the id column really a string? You've put single quotes around the value. MySQL will cast the string to an integer if needed, but if it's an integer, save the database some work and remove the single quotes.
try to echo $sql and run it directly in any database console, may be there is no record with id = $id
SQL Injection can be the answer. Not an intentional attack (at this moment), but if your parameters have some unexpected information like quotes or other reserved characters you can have strange results. So, try to run this SQL directly in your database administration utility.
Try doing this
"""update leads set
category="$Category",
type="$stype", etc...; """
See if that works