this is my connection class
class Connection {
public function query($sql){
mysql_connect('localhost','root','') or die("Connection error ". mysql_error());
mysql_select_db('liontours') or die("Database error ". mysql_error());
$results = mysql_query($sql);
$last_inserted_id = mysql_insert_id();
return array('results'=>$results, 'last_id'=>$last_inserted_id);
}
}
this is my model
public function V_reg($v_no, $dl_no, $owner, $o_name, $o_nic, $i_date, $ex_date, $p_report, $nic, $s_name, $f_name, $initials, $dob, $stat, $v_type) {
$sql = "INSERT INTO `vehicledetails`(`vehicle_no`, `owner`, `owner_name`, `owner_nic`, `insured_date`, `ex_date`, `police_report`,`type`)
VALUES ('$v_no','$owner','$o_name','$o_nic','$i_date','$ex_date','$p_report','$v_type')";
$conn = new Connection();
//vehicle id of last inserted record
$vehicle_id = mysql_insert_id();
$results = $conn->query($sql);
$last_vehicle_record_id = $results['last_id'];
$fk_key = $last_vehicle_record_id;
//checking the first table insert successful if so do the second insert else must define counter measure in else part
if ($fk_key !== 0) {
$sql1 = "INSERT INTO driverdetails (id, vehicle_id, nic,sir_name,first_name,dlNo,initials,dob,status )
VALUES ('null', '$fk_key', '$nic','$s_name','$f_name','$dl_no', '$initials','$dob','$stat')";
$results = $conn->query($sql1);
}else{
die('transaction failed').mysql_error();
}
return $results;
}
}
i don't know what is wrong with this coding but it's not passing the data all the time it says transaction failed and no error given. just the text can some body tell me any thing wrong with this coding ? if there is no coding errors is it a problem with my database ?
Related
The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this
I am trying to make register member page. If a new member insert an email which has been already exist, then there will be a notification saying that the email is exist. But if the email has not been exist, the values they insert in the form will be send to database.
I don't know what is wrong with my code bellow. It just blank and doesn't send anything to databse. I need a help.
<?php
//conection:
$link = mysqli_connect(".com","klaudia","intheclaud","elektro") or die("Error " . mysqli_error($link));
//consultation:
$member_id=$_GET['member_id'];
$member_name=ucwords(htmlspecialchars($_POST['member_name']));
$member_email=$_POST['member_email'];
$member_password=htmlspecialchars($_POST['member_password']);
$member_phone=$_POST['member_phone'];
$member_address_satu=ucwords(htmlspecialchars($_POST['member_address_satu']));
$member_address_dua=ucwords(htmlspecialchars($_POST['member_address_dua']));
$member_reference=$_POST['member_reference'];
$query = "SELECT * FROM member_registry WHERE member_email='$member_email '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)";
?>
I have tried to check the connection and the database. Everything works fine here. When I insert someone name which has been in the table of the database, it will echo that the email already exist. and vice versa.
$query = "SELECT * FROM member_registry WHERE member_name='Klaudia '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
echo "This email you are using has NOT been registered before";
}
[UPDATE]
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)");
}
?>
You shouldn't handle this by two separate queries (at least without a transaction).
Instead create a unique index that doesn't allow the same email address twice in the table and check for the specific ER_DUP_ENTRY error code to detect doublets.
sscce:
<?php
define('MYSQL_ER_DUP_ENTRY', 1062);
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_errno) {
trigger_error('connection failed', E_USER_ERROR);
}
$result = $mysqli->query('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
email varchar(128),
primary key(id),
unique key(email)
)'
);
if ( !$result) {
trigger_error('create table failed', E_USER_ERROR);
}
$stmt = $mysqli->prepare('INSERT INTO soFoo (email) VALUES (?)');
if (!$stmt) {
trigger_error('prepare failed', E_USER_ERROR);
}
$result = $stmt->bind_param("s", $email);
if ( !$result) {
trigger_error('bind_param failed', E_USER_ERROR);
}
foreach( array('email1', 'email2', 'email1') as $n=>$email ) {
echo $n, ' ', $email;
$result = $stmt->execute();
if ( $result ) {
echo " ok\r\n";
}
else {
if ( MYSQL_ER_DUP_ENTRY==$stmt->errno ) { // <-- here's the test for the duplicate entry
echo " duplicate\r\n";
}
else {
var_dump($stmt->errno, $stmt->error);
}
}
}
prints
0 email1 ok
1 email2 ok
2 email1 duplicate
You have an error in your syntax. You don't close your function.
Also you shouldn't use single quotes around your coumn names.
mysqli_query($link, "INSERT INTO member_registry (
`member_id`,
`member_name`,
`member_email`,
`member_password`,
`member_phone`,
`member_address_satu`,
`member_address_dua`,
`member_reference`)
VALUES (0,1,2,3,4,5,6,7,8)");
I'm connecting to a cloud database through an ODBC connection:
$conn = odbc_connect('MYDATABASE','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "SELECT DATETIME_ID, NAME, Sum(CNDROP) AS DATA
FROM MY_TABLE
WHERE DATETIME_ID>='2014-09-28:00:00:00'
and DATETIME_ID<='2014-09-28 23:00:00'
and NAME IN ('CC2')
GROUP BY DATETIME_ID, NAME ORDER BY DATETIME_ID, NAME";
$rs = odbc_exec($conn,$sql);
if (!$rs) {
exit("Consulta fallida");
}
$result = odbc_exec($conn,$sql) or die(exit("Error en odbc_exec"));
print odbc_result_all($result,"border=1");
odbc_close($conn);
I can get the data, and print the data, but now I need insert that data into a MySQL database into my computer.
I don't have any idea how to do it, so I need help with an example. I tried to search on google but nothing was helpful.
Option 1:
Function to SELECT
function get_data_from_cloud(){
$conn=odbc_connect('CLOUD','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT DATETIME, NAME, CNDROP
FROM TABLE1
WHERE DATETIME>='2014-09-28 00:00:00' and
DATETIME<='2014-09-28 23:00:00' and
NAME IN ('PETER')
GROUP BY DATETIME, NAME
ORDER BY DATETIME, NAME";
$result=odbc_exec($conn,$sql)or die(exit("Error en odbc_exec"));
$data = array();
while (odbc_fetch_row($result)) {
$data[]=array('DATETIME' => odbc_result ($result, "DATETIME"),
'NAME'=> odbc_result ($result, "NAME"),
'CNDROP'=> odbc_result ($result, "CNDROP"));
}
return $data;
}
Function to INSERT
function insert_cloud_data($cloud_data=array()){
$conn=odbc_connect('LOCAL','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
foreach($cloud_data as $data){
$sql = sprintf("INSERT INTO Prueba (DATIME, NAME, CNDROP)
VALUES ( '%s','%s','%s')",
$data['DATETIME'], $data['NAME'], $data['CNDROP']);
$rs = odbc_exec($conn,$sql);
if (!$rs) {
error_log("Consulta fallida");
}
}
odbc_close($conn);
}
Option 2:
Function to SELECT
function get_data_from_cloud(){
$conn=odbc_connect('CLOUD','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT DATETIME, NAME, CNDROP
FROM TABLE1
WHERE DATETIME>='2014-09-28 00:00:00' and
DATETIME<='2014-09-28 23:00:00' and
NAME IN ('PETER')
GROUP BY DATETIME, NAME
ORDER BY DATETIME, NAME";
$result=odbc_exec($conn,$sql)or die(exit("Error en odbc_exec"));
$data = array();
while (odbc_fetch_row($result)) {
$data[]=array(odbc_result ($result, "DATETIME"),
odbc_result ($result, "NAME"),
odbc_result ($result, "CNDROP"));
}
return $data;
}
Function to INSERT
function insert_cloud_data($cloud_data=array()){
$conn=odbc_connect('LOCAL','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "INSERT INTO Prueba (DATIME, NAME, CNDROP)
VALUES (?, ?, ?)";
$stmt = odbc_prepare($conn, $sql);
if(!$stmt) die("could not prepare statement ".$sql);
foreach($cloud_data as $data){
odbc_execute($stmt, $data);
}
odbc_close($conn);
}
USAGE
$cloud_data = get_data_from_cloud();
insert_cloud_data($cloud_data);
Here is different approach.
Create $conn1 (cloud) and $conn2 (localhost). Query the $conn1 then use php while and insert command into $conn2.
$conn1 = (cloud);
$conn2 = (localhost);
$query = "SELECT ...";
$result = odbc_exec($conn1,$query);
while( fetch result data ) {
$query = "INSERT ....";
odbc_exec($conn2,$query);
}
Scenario:
I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})
The data types are correct.
I need to now get the latest IDENTIY which is GradeID.
I have tried the following after consulting MSDN and StackOverflow:
SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
The next thing I tried, SELECT ##IDENTITY Still to no avail.
Lastly, I tried PDO::lastInsertId() which did not seem to work.
What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.
Expected Results:
Just to return the newly inserted row's IDENTITY.
Current Results:
It returns it but is NULL.
[Object]
0: Object
ID: null
This piece pasted above is the result from print json_encode($newID); as shown below.
Notes,
This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.
As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks
Code:
for ($i=0; $i < sizeof($grades); $i++) {
$grade = $grades[$i];
$oldID = $grade->GradeID;
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";
try {
$sqlObject->executeNonQuery($query);
$query = "SELECT SCOPE_IDENTITY() AS ID";
$newID = $sqlObject->executeQuery($query);
print json_encode($newID);
} catch(Exception $e) {
print json_encode($e);
}
$gradesDictionary[] = $oldID => $newID;
}
EDIT #1
Here is the code for my custom wrapper. (Working with getting the lastInsertId())
class MSSQLConnection
{
private $connection;
private $statement;
public function __construct(){
$connection = null;
$statement =null;
}
public function createConnection() {
$serverName = "localhost\MSSQL2014";
$database = "{Fill In}";
$userName = "{Fill In}";
$passWord = "{Fill In}";
try {
$this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
$this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die("Connection Failed, please contact system administrator.");
}
if ($this->connection == null) {
die("Connection Failed, please contact system administrator.");
}
}
public function executeQuery($queryString) {
$results = array();
$this->statement = $this->connection->query( $queryString );
while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
array_push($results, $row);
}
return $results;
}
public function executeNonQuery($queryString) {
$numRows = $this->connection->exec($queryString);
}
public function getLastInsertedID() {
return $this->connection->lastInsertId();
}
public function closeConnection() {
$this->connection = null;
$this->statement = null;
}
}
This is PDO right ? better drop these custom function wrapper...
$json = array();
for ($i=0; $i < sizeof($grades); $i++) {
//Query DB
$grade = $grades[$i];
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$success = $stmt->execute(array($grade->Name,
$grade->Capacity,
$grade->SpringPressure));
//Get Ids
$newId = $conn->lastInsertId();
$oldId = $grade->GradeID;
//build JSON
if($success){
$json[] = array('success'=> True,
'oldId'=>$oldId, 'newId'=>$newId);
}else{
$json[] = array('success'=> False,
'oldId'=>$oldId);
}
}
print json_encode($json);
Try the query in this form
"Select max(GradeID) from dbo.Grades"
So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.