I've setup an EE template with PHP enabled and set the PHP Parsing Stage as Input. I would expect the following code to update the database correctly, but nothing happens:
<?php
$ids= "{last_segment}";
$userId = "{member_id}";
$sql = "UPDATE table SET column = '" . $ids . "' WHERE member_id = '" . $userId . "'";
$this->EE->db->query($sql);
?>
If I echo my query it looks correct, and in fact if I run it in PHPMyAdmin it works fine. Is there something I'm missing? Do I need to modify the PHP Parsing Stage?
Thanks in advance!
Looks like you may just need parentheses after "EE":
$this->ee()->db->query($sql);
Also, I'm not sure if you need $this...
http://ellislab.com/expressionengine/user-guide/development/usage/database.html
Related
I have a query which is not inserting if i use the where clause, without the where clause it inserts data. this is weird and I have never seen it happen before in WAMP
$key=substr(md5(rand(0, 1000000)), 0, 5);
$key1="INSERT INTO login(key_id) VALUES('$key')
WHERE (email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')"
if(mysql_query($key1))
{
$message = 'User Added!.';
echo "<SCRIPT>
alert('$message');
location='forgotpassword.php';
</SCRIPT>";
}
If I echo $_POST['email_id'] it does return valid result
INSERT and WHERE do not mix.
when INSERTing, you are creating a new record.
WHERE is used with SELECTing DELETEing or UPDATEing, when you have to specify a filter which rows you want to SELECT, DELETE or UPDATE.
if you want to INSERT a row, do not use WHERE.
if you want to change a row, use
$key1="UPDATE login SET key_id = '$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
Insert is only used on creating new record and where clause is only used if want to set any condition it is used with like select,update,delete.
Try this it will help:-
$key1="update login set key_id ='$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
I know #Franz-Gleichmann is already explained very well, whats wrong in your code.
You need to use UPDATE for updating data modified code:
$key1 = "UPDATE login SET key_id = '$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
Now i am adding two more points:
Please use mysqli_* or PDO, because mysql_* is deprecated and not available in PHP 7.
You missed the termination semi colon on the same line, i hope this is typo error.
I've been trying to make this code work for hours now but I can't seem to find solution. I've serached all relevant topics and tried to change the code, punctuation etc. but none of them worked for me.
The result is always "Success!" but the database update never works (checked in phpmyadmin).
I hope that you can find the error. The code is the following:
if(empty($_POST['nev']) || empty($_POST['orszag']) || empty($_POST['telefonszam']) || empty($_POST['iranyitoszam'])
|| empty($_POST['megye']) || empty($_POST['varos']) || empty($_POST['utca'])) {
echo "Failure! Missing data...";
}
else {
$nev = mysql_real_escape_string($_POST['nev']);
$orszag = mysql_real_escape_string($_POST['orszag']);
$telefonszamm = mysql_real_escape_string($_POST['telefonszam']);
$iranyitoszam = mysql_real_escape_string($_POST['iranyitoszam']);
$megye = mysql_real_escape_string($_POST['megye']);
$varos = mysql_real_escape_string($_POST['varos']);
$utca = mysql_real_escape_string($_POST['utca']);
$shipping_query = mysql_query("UPDATE users
SET Name=".$nev.", Phone=".$telefonszam.",
Country=".$orszag.", State=".$megye.",
City=".$varos.", ZIP=".$iranyitoszam.",
Road=".$utca."
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
echo "Success!";
}
Thank you for your help!
You're missing quotes around the strings in your query.
$shipping_query = mysql_query("UPDATE users
SET Name='".$nev."', Phone='".$telefonszam."',
Country='".$orszag."', State='".$megye."',
City='".$varos."', ZIP='".$iranyitoszam."',
Road='".$utca."'
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
You also no error checking on your query. So whether it succeeds or fails it will always say, "success". You need to check to see if there is a MySQL error ir rows updated before you can declare success.
Name, Phone, Country etc etc seam like VARCHARs. so, it should be treated as a string.
So, query should be like.
"UPDATE users SET Name='".$nev."', Phone='".$telefonszam."',Country='".$orszag."', State='".$megye."',City='".$varos."', ZIP='".$iranyitoszam."',Road='".$utca."' WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'"
As other answers have pointed out, you're missing quotes around your string variables.
When you're MySQL queries are failing to execute, try echoing your queries while debugging to see what exactly you're sending to the database.
$myValue = "Green";
$mySQL = "UPDATE MyTable SET MyColor = " . $myValue;
$myQuery = mysql_query($mySQL);
echo $mySQL;
Spotting the error visually is much easier when the entire SQL string is assembled in one piece.
You can also copy the assembled SQL string and paste it straight into a phpmyadmin query to get debugging information from it.
Hey I am currently trying to insert a global variable to a table. The other values I pass are variables too but they get sent correctly.
Here is my query. my error handling does not capture anything
$result = mysql_query("INSERT INTO IPmanagement (userId, NameUsed, EmailUsed, IPStatus, Ip) VALUES ('" .$masterUserId . "', '" . $Entry['LeadName'] . "', '" . $Entry['LeadEmail'] . "', '0', '" . $ip . "')") or die(ErrorException("Function 6", "Error when processing the current lead. your data is unaffected and if the proccess continues please contact an Admin.", mysql_error(),$_SERVER['REMOTE_ADDR'], CurrentPath(), $masterUserId));
my variable that is global defined before the function is
$masterUserId = "1";
I tried echoing the variable before it sends and it echos out correctly YET my table holds a value of 0.
here is a screenshot of how I have my table setup.
Click for Larger Image
Any idea what is going on. I am rather stumped and tried writing this same code different ways and it still gives me same issue. Also $masterUserId will always be an int value
Edit: also would like to mention the variable is different .php that contains the varaiable and database login information. It is being included at the top. (don't know if that is relevant)
Because you are not inserting IP STATUS.Which is not null
\
You should either set this to null or enter some value to it.
If you are using query in a function than use like this
function (){
//than define
$globat $masterUserId;
// use the global defination
// than use this variable with global value
}
Do not use mysql_*. Replace them with mysqli_* or PDO::.
Did you try to echo the mysql_query()? Do this. Replace mysql_query("..."); with die("..."); and put it in the phpMyAdmin and try executing.
And in your table, I see that IP Status is a NOT NULL. So that might throw an exception. Use a default value in the table.
And yeah, what do you get the result as in mysql_error()?
Why ''' or "' in query?
I have cleaned up query with PHP function sprintf and using NULL for EntryID(Autoincrement)
$query = sprintf("INSERT INTO IPmanagement (EntryID,userId, NameUsed, EmailUsed, IPStatus, Ip) VALUES (NULL,%s,%s,%s,'0',%s)",
$masterUserId , $Entry['LeadName'] , $Entry['LeadEmail'] , $ip ));
$result = mysql_query($query);
You should also use MySQLi or PDO
I've two mysql tables, here is sql for them =>
I'm making dynamic menu with its sub menu . SO I've the situation that want to execute such a query
DELETE FROM artinfo WHERE descName=(SELECT for_sub_url FROM menu WHERE menu_id=" . $_POST['main_menu_titles'] . ")
where $_POST['main_menu_titles'] exists and is menu_id. I'm not writing php code too , because it works just fine and remarkable is that , this query executes when I am trying to execute it from mysql shell (of course using directly number of menu_id instead of $_POST['m_num'])
Any ideas whats going on, how to execute it from php script ? thanks :)
UPDATE
here is php script
if ($connection->query("DELETE FROM artinfo WHERE descName=(SELECT for_sub_url FROM menu WHERE menu_id=" . $_POST['main_menu_titles'] . ")") && $connection->query("DELETE FROM artinfo WHERE descName IS NULL AND cat_id=" . $_POST['main_menu_titles'] . "")){
$edit_res_fine = "DELETED";
}
If you say the query works just fine without $_POST, I would think the code in question is located in the form you submit to acquire $_POST['main_menu_titles']. To test the correct value is being sent, try echoing the value of $_POST['main_menu_titles'] right before the query.
Try this.
$query = "DELETE FROM artinfo WHERE descName = (SELECT for_sub_url FROM menu
WHERE menu_id = '" . $_POST['m_num'] . "')";
I'm doing well with CodeIgniter. I can do SELECT statements on my MySQL database with no problems at all. But, now I'm trying to do an INSERT statement.
Note that I have not tried an UPDATE statement yet.
After reading the docs, I'm so confused.
This is what I have:
contacts.php:
function add() {
//echo "<pre>";print_r($_POST);
$this->load->model('Contacts_model');
$this->Contacts_model->insertContact($_POST);
}
contacts_model.php:
function insertContact($_POST) {
//echo "<pre>";print_r($_POST);
$title = $_POST['title']; // I can echo this here. It works
$f_name = $_POST['f_name']; // I can echo this here. It works
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES (" .
$this->db->escape($title) .
"," .
$this->db->escape($f_name) .
")";
$this->$db->query($sql);
}
I've read about Active Record, but if that's what is messing me up, then I still don't realize what I'm doing wrong. All of the examples look exactly like mine.
Help?
EDIT
$sql = "INSERT INTO contacts (title,f_name) VALUES ('$this->db->escape($title)','$this->db->escape($f_name)'";
$this->$db->query($sql);
I've also tried it like this. And many other variants. It doesn't seem to be my syntax... I think.
Your query is fine, only reason that why query is not being executed is that you are using this:
$this->$db->query($sql);
there is nothing like $db, just use this:
$this->db->query($sql);
I'm sure this is the problem, but if it is not then please kindly post the error what it is giving. Thanks.
Hope this helps.
You missed the quote character:
$title = $this->db->escape($title);
$fname = $this->db->escape($f_name)
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES ('{$title}', '{$fname}')";
$this->db->query($sql);
BTW, What the hell with the $_POST variable? It's one of SuperGlobal variable. You don't have to transfer it in parameter. You can always safely call it anywhere in your script.
Another note, since you use CodeIgniter, you better check out the Input class library and use it for all your input need.
Why send $_POST? Use $this->input->post("param_name") and in your instance "$this->load->model('Contacts_model');" in my practice i use "$this->load->model('Contacts_model','instance',[true or false]);" the last parameter is optional (to connect with the DB if you don't use autoload option).
Use this:
function insertContact() {
$title = $this->input->post("title");
$f_name = $this->input->post("f_name");
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES ('" . $this->db->escape($title) . "','".$this->db->escape($f_name) ."')";
$this->$db->query($sql);
}
DON'T USE $_POST! (And use the Active Record read the user guide)