insert query through php doesn't update MySQL database - mysql
I have user input coming in from a form (possible null fields - yes, the database is set up to work with null values), and I need to insert the information into a table in the database.
Just some more information: I'm making this application in Titanium
This is the code that sends all the parameters to the PHP file:
saveButton.addEventListener('click', function() {
var xhr = Ti.Network.createHTTPClient();
var url = ""; //url is in here; I just took it out for privacy
xhr.open("GET", url);
var params = {
query : "enterAsset",
barcode : barcodeTextField.value, //all these textfields are editable by the user
assetClass : assetClassTextField.value,
manufacturer : manufacturerTextField.value,
model : modelTextField.value,
serialNum : serialNumTextField.value,
custodian : custodianTextField.value,
status : statusTextField.value,
loginName : LOGIN_NAME,
divisionID : DIVISION_ID,
dateBuy : dateBoughtTextField.value,
priceBuy : priceTextField.value,
dateInSvc : dateInServiceTextField.value,
dateLastSvc : dateLastServiceTextField.value,
};
xhr.onload = function() {
alert("Successful entry"); //this alert does appear when the button is pressed
};
xhr.send(params);
});
This is the code in the PHP file after connecting to the database:
$query = $_GET['query'];
switch($query) { //this switch statement exists so we can access the database for multiple queries from the same .php file. We know it works because the "login" query works just fine.
case "data":
//unimportant stuff is in here
break;
case "clients":
//more irrelevant stuff in here
break;
case "login": //this works, but it's not trying to insert anything
$username = $_GET['username'];
$password = $_GET['password'];
$stmt4 = $con->prepare('CALL Get_user_auth(:username,:password)');
$stmt4->bindParam(':username',$username,PDO::PARAM_STR);
$stmt4->bindParam(':password',$password,PDO::PARAM_STR);
$stmt4->execute();
$results = $stmt4->fetchAll(PDO::FETCH_ASSOC);
$stmt4->closeCursor();
break;
case "search":
//more irrelevant stuff in here
break;
case "enterAsset":
$barcode = '12345';
$assetClass = 'test';
$manufacturer = 'test';
$model = 'test';
$serialNum = 'test';
$custodian = 'test';
$locationID = '1';
$status = 'test';
$dateBuy = 'test';
$priceBuy = 'test';
$dateInSvc = 'test';
$dateLastSvc = 'test';
$loginName = 'jane';
$divisionID = '1';
$stmt6 = $con->prepare('CALL Enter_new_asset(:divisionID,:barcode,:assetClass,:manufacturer,:model,:serialNum,:custodian,:status,:locationID,:dateBuy,:priceBuy,:dateInSvc,:dateLastSvc,:loginName)');
$stmt6->bindParam(':divisionID',$divisionID,PDO::PARAM_INT,11);
$stmt6->bindParam(':barcode',$barcode,PDO::PARAM_STR,128);
$stmt6->bindParam(':assetClass',$assetClass,PDO::PARAM_STR,10);
$stmt6->bindParam(':manufacturer',$manufacturer,PDO::PARAM_STR,10);
$stmt6->bindParam(':model',$model,PDO::PARAM_STR,10);
$stmt6->bindParam(':serialNum',$serialNum,PDO::PARAM_STR,20);
$stmt6->bindParam(':custodian',$custodian,PDO::PARAM_STR,20);
$stmt6->bindParam(':status',$status,PDO::PARAM_STR,10);
$stmt6->bindParam(':locationID',$locationID,PDO::PARAM_INT,11);
$stmt6->bindParam(':dateBuy',$dateBuy,PDO::PARAM_STR,13);
$stmt6->bindParam(':priceBuy',$priceBuy,PDO::PARAM_STR,10);
$stmt6->bindParam(':dateInSvc',$dateInSvc,PDO::PARAM_STR,13);
$stmt6->bindParam(':dateLastSvc',$dateLastSvc,PDO::PARAM_STR,13);
$stmt6->bindParam(':loginName',$loginName,PDO::PARAM_STR,20);
$stmt6->execute();
$stmt6->closeCursor();
break;
default:
$results = "FAIL.";
break;
}
This returns "null" when I specify the "enterAsset" query, which is expected because it shouldn't be returning anything.
The stored query for Enter_new_asset is:
INSERT INTO TBL_ASSET_DATA (Division_ID, Barcode_Tag, Asset_Class, Manufacturer, Model, Serial_Num, Custodian, Status, Location_ID, Date_buy, Price_buy, Date_in_svc, Date_last_svc, Updated_by)
VALUES(divisionID,barcode, assetClass, manufacturer, model, serialNum, custodian, status, locationID, dateBuy, priceBuy, dateInSvc, dateLastSvc, loginName)
EDIT: I tried hardcoding in some values for the variables, and now I'm getting this error: Parse error: syntax error, unexpected '';' (T_CONSTANT_ENCAPSED_STRING) in /homepages/21/d265224452/htdocs/brillient_wordpress/AMproxy.php on line 90
This is the code at line 90:
$stmt6 = $con->prepare('CALL Enter_new_asset(:divisionID,:barcode,:assetClass,:manufacturer,:model,:serialNum,:custodian,:status,:locationID,:dateBuy,:priceBuy,:dateInSvc,:dateLastSvc,:loginName)');
My question is: Why is the database not updating with the entered information? A new entry is not appearing in the TBL_ASSET_DATA. Other questions with this issue seem to be using MySQLi or the deprecated mysql commands, and this is using PDO.
Thank you for your help in advance.
EDIT I got my database to update by replacing
$stmt6 = $con->prepare('CALL Enter_new_asset(:divisionID,:barcode,:assetClass,:manufacturer,:model,:serialNum,:custodian,:status,:locationID,:dateBuy,:priceBuy,:dateInSvc,:dateLastSvc,:loginName)');
with:
$sql = "INSERT INTO TBL_ASSET_DATA(Division_ID, Barcode_Tag, Asset_Class, Manufacturer, Model, Serial_Num, Custodian, Status, Location_ID, Date_buy, Price_buy, Date_in_svc, Date_last_svc, Updated_by) VALUES(:divisionID,:barcode, :assetClass, :manufacturer, :model, :serialNum, :custodian, :status, :locationID, :dateBuy, :priceBuy, :dateInSvc, :dateLastSvc, :loginName)";
$stmt6 = $con->prepare($sql);
but I'm wondering whether this is secure.
You seem to be missing a quote to close your string here:
$dateLastSvc = 'test;
This is making you code behave incorrectly. You can easily pick ushc typo errors if using an editor with context highlighting. For example, I could pick this up right away in looking at the highlighting that even Stack Overflow does.
Related
Get data from another Database in Codeigniter MySQL
I want to get data from another DB in MySQL except the defualt DB. I added the following line into my model in addition to the excisting code. Another DB as 'storesDB'. $this->load->database('storesDB', TRUE); My model as follows : public function getEquipment($id = null) { $this->db->select('*'); $this->db->from('tbl_equipment'); $this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat'); $this->db->where("tbl_equipment.status", '1'); if ($id) $this->db->where("tbl_equipment.id", $id); $query = $this->db->get(); return $query->result(); } The code is working properly. But the code got data from defualt DB not the by the 'storesDB'. Modified code is as follows : public function getEquipment($id = null) { $this->load->database('storesDB', TRUE); $this->db->select('*'); $this->db->from('tbl_equipment'); $this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat'); $this->db->where("tbl_equipment.status", '1'); if ($id) $this->db->where("tbl_equipment.id", $id); $query = $this->db->get(); return $query->result(); } What may be the reason?
The reason is that you don't assign the second database properly. You also need to setup the correct config for the 2nd database $config['hostname'] = "host"; $config['username'] = "user"; $config['password'] = "pass"; $config['database'] = "storesDB"; // etc.. then you load the database: $this->db2 = load->database($config, TRUE); now you have $this->db, the default database and $this->db2, the second database and continue your code like: $this->db2->select('*'); $this->db2->from('tbl_equipment'); // etc...
I have no experience in Codeigniter, but in a standar sql query you can add the database name in front of the table to get info from another db like: SELECT * FROM sakila.actor; Assuming you are not connected to sakila db. Using this aproach both databases must have same credentials
Is there any way to set a special character in MySQL database record?
I used CodeIgniter for my back end technology. I just create one bulk insertion module for reading CSV data and insert it in the database. But in insertion do not insert proper value like:- Wrong value:- Brhl Castle Right value:- Brühl Castle Is there any way to insert the same value in a database like the right value? In Controller my code like this:- $dataIn['title'] = utf8_encode($data[1]); $dataIn['latitude'] = $data[2]; $dataIn['longitude'] = $data[3]; $dataIn['country'] = utf8_encode($data[4]); $dataIn['city'] = utf8_encode($data[5]); $this->model->bulkInsert($dataIn); In Model my code like this:- function bulkInsert($dataIn, $id = '') { $this->db->where(array('id' => $dataIn['id'])); $query = $this->db->get($this->TABLE); $result = $query->row_array(); if ($query->num_rows() > 0) { $this->db->where($this->PK, $dataIn['id']); $this->db->update($this->TABLE, $dataIn); } else { $this->db->insert($this->TABLE, $dataIn); } setMessage('Record inserted successfully.', 'green'); }
How to conditionally use different database in CodeIgniter
Here is my scenario. A user will login to the system. Based on the username, I need to set the database in codeigniter configuration. I know that the line $this->load->database() in each model loads the default database. So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database? Below is something that I am looking for: if(username == 'foo'){ $this->load->database('database_name'); } An example of a model function that I have written is as follows: public function check_valid_login($username, $password){ $this->db->from('tbl_user_details'); $this->db->where('email_address', $username); $this->db->where('password', md5($password)); $query = $this->db->get(); $rowcount = $query->num_rows(); return $rowcount ; } On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?
I think I found a solution. This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user. The following logic is used for selecting the database dynamically. The below code is written in config/database.php /*Dynamic database selection - begins*/ if(!empty($_SESSION['dynamic_db_username'])){ $dynamic_db_username = $_SESSION['dynamic_db_username']; if($dynamic_db_username == 'sample#domain.com') { $db['default']['database'] = 'database_1'; } elseif($dynamic_db_username == 'sample2#domain.com') { $db['default']['database'] = 'database_2'; } else { $db['default']['database'] = 'database_1'; } } else { $db['default']['database'] = 'database_1'; } /*End*/ Kindly review this strategy and please let me know if this is right.
in the config folder there was a file named autoload.php open the file find first this code below $autoload['libraries'] = array(''); you have to put "database" in the array , changed code will be like $autoload['libraries'] = array('database'); after that you can use your database anytime and anywhere without loading it manually .
Statements works in SQL, but not in PDO
I'm converting from SQL to PDO, and everything has gone well until this statement. My SQL does what it should and does NOT output the message "This user has no private images". But for some reason, when changing to PDO, the same message is shown when it should not be. Any ideas? Original SQL: $result = mysql_query("SELECT * FROM tbl_private_photos WHERE profile = $usernum AND photo_deleted != 'Yes' LIMIT 1"); if (mysql_num_rows($result)!==1) { die("This user has no private images");} My PDO: $sql = "SELECT * FROM tbl_private_photos WHERE profile = :usernum AND photo_deleted != 'Yes' LIMIT 1"; $q = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that $q->bindValue(':usernum',$usernum,PDO::PARAM_INT); $q->execute(); if($r = $q->fetch(PDO::FETCH_ASSOC)!==1) { die("This user has no private images"); }
PDO::fetch() returns in this case an array or false. You don't want to compare the fetch result explicitly to the integer 1 then assign it to a variable--it will always be true because a 1 !== array() is always true, and 1 !== false is always true. Instead you should see if your result set is empty or false. Try this instead: $r = $q->fetch(PDO::FETCH_ASSOC); if(empty($r)) { die("This user has no private images"); }
Doctrine Native SQL many-to-many query
I have a many-to-many relationship between Students and Programs with tables student, program, and student_program in my database. I'm trying to join the two entities and perform some custom queries that require subqueries. This means that the Doctrine QueryBuilder cannot work because it does not support subqueries. Instead, I'm trying the NativeSQL function and am making decent progress. However, when I try to SELECT something from the Program entity, I get the error Notice: Undefined index: Bundle\Entity\Program in vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php line 180. $mapping = new \Doctrine\ORM\Query\ResultSetMappingBuilder($em); $mapping->addRootEntityFromClassMetadata('Student', 's'); $mapping->addJoinedEntityFromClassMetadata('Program', 'p', 's', 'programs', array('id' => 'program_id')); // Query based on form $sql = 'SELECT s.id, s.last_name, p.name <---- problem when this is added FROM student s JOIN program p '; $query = $em->createNativeQuery($sql, $mapping); $students = $query->getResult();
Not a direct answer but doctrine 2 does indeed support sub queries. Just create a query then feed the dql into a where class. This example is somewhat verbose but it works just fine: public function queryGames($search) { // Pull params $ages = $this->getValues($search,'ages'); $genders = $this->getValues($search,'genders'); $regions = $this->getValues($search,'regions'); $sortBy = $this->getValues($search,'sortBy',1); $date1 = $this->getValues($search,'date1'); $date2 = $this->getValues($search,'date2'); $time1 = $this->getValues($search,'time1'); $time2 = $this->getValues($search,'time2'); $projectId = $this->getValues($search,'projectId'); // Build query $em = $this->getEntityManager(); $qbGameId = $em->createQueryBuilder(); // ### SUB QUERY ### $qbGameId->addSelect('distinct gameGameId.id'); $qbGameId->from('ZaysoCoreBundle:Event','gameGameId'); $qbGameId->leftJoin('gameGameId.teams', 'gameTeamGameId'); $qbGameId->leftJoin('gameTeamGameId.team','teamGameId'); if ($projectId) $qbGameId->andWhere($qbGameId->expr()->in('gameGameId.projectId',$projectId)); if ($date1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.date',$date1)); if ($date2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.date',$date2)); if ($time1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.time',$time1)); if ($time2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.time',$time2)); if ($ages) $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.age', $ages)); if ($genders) $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.gender',$genders)); if ($regions) { // $regions[] = NULL; // $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.org', $regions)); $qbGameId->andWhere($qbGameId->expr()->orX( $qbGameId->expr()->in('teamGameId.org',$regions), $qbGameId->expr()->isNull('teamGameId.org') )); } //$gameIds = $qbGameId->getQuery()->getArrayResult(); //Debug::dump($gameIds);die(); //return $gameIds; // Games $qbGames = $em->createQueryBuilder(); $qbGames->addSelect('game'); $qbGames->addSelect('gameTeam'); $qbGames->addSelect('team'); $qbGames->addSelect('field'); $qbGames->addSelect('gamePerson'); $qbGames->addSelect('person'); $qbGames->from('ZaysoCoreBundle:Event','game'); $qbGames->leftJoin('game.teams', 'gameTeam'); $qbGames->leftJoin('game.persons', 'gamePerson'); $qbGames->leftJoin('game.field', 'field'); $qbGames->leftJoin('gameTeam.team', 'team'); $qbGames->leftJoin('gamePerson.person', 'person'); $qbGames->andWhere($qbGames->expr()->in('game.id',$qbGameId->getDQL())); // ### THE TRICK ### switch($sortBy) { case 1: $qbGames->addOrderBy('game.date'); $qbGames->addOrderBy('game.time'); $qbGames->addOrderBy('field.key1'); break; case 2: $qbGames->addOrderBy('game.date'); $qbGames->addOrderBy('field.key1'); $qbGames->addOrderBy('game.time'); break; case 3: $qbGames->addOrderBy('game.date'); $qbGames->addOrderBy('team.age'); $qbGames->addOrderBy('game.time'); $qbGames->addOrderBy('field.key1'); break; } // Always get an array even if no records found $query = $qbGames->getQuery(); $items = $query->getResult(); return $items; }