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)
Related
In the first variable I store the name of a picture. The second one stores the path to this picture. The MySQL field should get both of them in order so I can access it from browser. How can I do this? I've already tried this:
$path = 'www.something.com/images/';
$sql = "INSERT INTO tb_user_info " . "(user_image)"."VALUES( '$path'.'$user_pic')";
Well first of all, you should be using prepared statements with mysqli or pdo. But to answer your question.
$path = 'www.something.com/images/' . $user_pic;
$sql = "INSERT INTO tb_user_info (user_image) VALUES( '$path')";
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 have a form that takes in a number of fields about a camera's details. This is a custom page I'm creating on Joomla. First I get the database object:
$db = &JFactory::getDBO();
Process the camera name entered in the form and add to DB:
$add_name = $_POST['camera_name'];
$query_insert_camera = "INSERT INTO #__cameras (camera_name, ... , user_id) VALUES ('".mysql_real_escape_string($add_name)."', ... ,'".$user->id."')";
$db->setQuery($query_insert_camera);
$db->query();
I just get an empty string for camera name. If I take out mysql_real_escape_string it works fine. I'm guessing mysql_real_escape_string doesn't like the way I'm establishing a connection...I think.
Any ideas?
You may want to look into JRequest::getVar http://docs.joomla.org/Retrieving_and_Filtering_GET_and_POST_requests_with_JRequest::getVar
However, it doesn't appear that it can be used in a module: http://groups.google.com/group/joomla-dev-general/browse_thread/thread/15ebde03b858c9e8
I just came across the issue of using mysql(i)_real_escape_string() within Joomla, and found that I needed to pass in the db connection as the first parameter:
$db = JFactory::getDbo();
$myVar = JRequest::getVar('myVarName');
$mysqlSafeVar = msqli_real_escape_string($db->getConnection(), $myVar);
$sql = 'INSERT INTO #__mytable (' .$db->nameQuote('myField'). ') VALUES (' . $db->quote($mysqlSafeVar) . ')';
$success = $db->execute();
Your code should work. I see mysql_real_escape_string() being used almost the same way here.
The difference between that code, and what you have is minor, but maybe try something like this instead:
$db = &JFactory::getDBO();
// Escape the POST var as you grab it
$add_name = mysql_real_escape_string(JRequest::getVar('camera_name', '', 'post', 'string'));
$query_insert_camera = "INSERT INTO #__cameras (camera_name) VALUES ('" . $add_name . "')";
$db->setQuery($query_insert_camera);
$db->query();
HI
I am getting Resource#6 and Resource#7 when I print the following variables:
$salty_password = sha1($row['salt'], $_POST['password']);
if(isset($_POST['subSignIn']) && !empty($_POST['email']) && !empty($_POST['password'])) {
$query = "SELECT `salt` FROM `cysticUsers` WHERE `Email` = '" . $_POST['email'] . "'";
$request = mysql_query($query,$connection) or die(mysql_error());
$result = mysql_fetch_array($request);
$query2 = "SELECT * FROM `cysticUsers` WHERE `Email` = '". $_POST['email']."' AND `Password` = '$salty_password'";
$request2 = mysql_query($query2,$connection) or die(mysql_error());
$result = mysql_fetch_array($request2);
print_r($request);
print_r($request2);
if(#mysql_num_rows($request,$request2)) {
$_SESSION['CLIFE']['AUTH'] = true;
$_SESSION['CLIFE']['ID'] = $result['id'];
// UPDATE LAST ACTIVITY FOR USER
$query = "UPDATE `cysticUsers` SET `LastActivity` = '" . date("Y-m-d") . " " . date("g:i:s") . "' WHERE `id` = '" . mysql_real_escape_string($_SESSION['CLIFE']['ID']) . "' LIMIT 1";
mysql_query($query,$connection);
if(!empty($_POST['return'])) {
header("Location: " . $_POST['return']);
}else{
header("Location: CysticLife-Dashboard.php?id=" . $_SESSION['CLIFE']['ID']);
}
}
}else{
$_SESSION['CLIFE']['AUTH'] = false;
$_SESSION['CLIFE']['ID'] = false;
}
?>
Trying to troubleshoot this code chunk and not sure what that means. I am trying to sign back in with the clear text password I signed up with after its been hashed and salted. I feel like I'm very close but something is slightly wrong. Help on why that is not working would be greatly appreciated as well.
Thanks in advance
mysql_query() returns result sets as objects of type resource (they're not objects in terms of PHP OOP code but I can't think of a better word). These contain binary data that can only be read by certain functions, for example the mysql_fetch_*() functions.
To debug your MySQL queries you should check for errors using mysql_error() and mysql_errno() and/or save your SQL statements in variables and print those.
From what I see, you're performing two queries but overwriting the same $result variable, without doing anything about the first. Also, mysql_num_rows() can only count one result set at a time, so you can't pass two result sets into the same call.
Those are PHP's internal data types called resource.
They cannot be serialized (i.e. there's no "toString()") and are hence displayed as Resource#X.
SQL queries through PHP are done using a variable known as a resource. This variable, in your code, is completely useless other than to pass to each function you want to perform (i.e. change a database, execute a query, grab the last error, etc.).
That being said, executing a query doesn't return any information from the database, just a reference to that record set (where in PHP it's storing the information). You would then use that variable in a call such as mysql_fetch_array to retrieve the actual row information.