MySQL insert not working on new table - php

I am doing an insert on the MySQL table "analytics" with the fields "a_id" (PRIMARY and UNIQUE), "a_query" and "a_date".
My code:
function queryanalytics($clsendquery) {
$datetime = date("Y-m-d H:i:s");
$connection = connectsql();
$sql = "INSERT INTO analytics (a_query,a_date) VALUES (?,?)";
$stmt = $connection->prepare($sql);
$stmt->bind_param('ss',$clsendquery,$datetime);
$stmt->execute;
$stmt->close();
}
Nothing updates in the database and $stmt->affected_rows returns 0.
There are no errors in $stmt->error or $connection->error.
When I run the insert in phpMyAdmin it works fine.
I have other selects and inserts that work fine with the same connection, why does this one not?
Please help me.

$stmt->execute; should be $stmt->execute();

Related

Problem inserting data into SQL Server via PHP

I have a problem with an insert query in PHP.
I'm trying to insert data to SQL Server database.
The query is correctly executed, but the string value are modified.
\0 (null) are inserted between each character.
For example :
GeoFOA is inserted like that \0\0\0G\0\0\0e\0\0\0o\0\0\0F\0\0\0O\0\0\0A
Here's my code : all params had been verified, and they didn't contain any \0
$DateTimeNow = date("Y-m-d H:i:s") ;
$params = array($IdApp, $Un, $Mn, $Dn, $Mid, $Ip, $DateTimeNow, $ValidLic, $LogMessage);
$sql = "INSERT INTO [dbo].[LOGS]
(IDAPPLICATION, USERNAME, MACHINENAME, DOMAINNAME, MACADRESS, PUBLICIP, ACCESSDATE, VALIDLICENCE, COMMENT)
VALUES (?,?,?,?,?,?,?,?,?)";
$stmt = sqlsrv_query( $conn, $sql, $params);
$rows_affected = sqlsrv_rows_affected( $stmt);
There is no errors.
$rows_affected return true.
But when I tried to display result in SSMS with SELECT query field are displayed empty.
If I load the table on edit mode via SSMS, field are not empty, but not editable.

Get last inserted ID in prepared statement

I need to get the last inserted ID for each insert operation and put it into array, I am trying to see what is the correct way of doing it.
Following this post Which is correct way to get last inserted id in mysqli prepared statements procedural style?
I have tried to apply it to my code but I am still not getting the right response.
if($data->edit_flag == 'ADDED')
{
$rowdata[0] = $data->location_name;
$rowdata[1] = 0;
$rowdata[2] = $data->store_id;
$query = "INSERT IGNORE INTO store_locations (location_name,total_items, store_id) VALUES (?,?,?)";
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = mysqli_stmt_insert_id($statement);
echo "inserted id: " . $id;
}
I then realised that I am using a PDO connection so obviously mysqli functions wont work. I went ahead and tried the following
$id = $conn->lastInsertId();
echo "insert id: " . $id;
but the response is still empty? What am I doing incorrectly? For the lastInsertId(), should I be using $conn or $statement from here:
$statement = $conn->prepare($query);
$statement->execute($rowdata);
You are using lastInsertId() correctly according to the PDO:lastInsertId() documentation
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = $conn->lastInsertId();
Some potential reasons why it is not working:
Is this code within a TRANSACTION? If so, you need to COMMIT the transaction after the execute and before the lastInsertId()
Since you INSERT IGNORE there is the potential that the INSERT statement is generating an error and not inserting a row so lastInsertId() could potentially be empty.
Hope this helps!
If you are using pdo,
$stmt = $db->prepare("...");
$stmt->execute();
$lastInsId = $db->lastInsertId();

Insert at specific 'ID' into my table.

I need to write a PHP script using a database for school. Since my MySQL skills are currently dying, I would like to ask following question:
Following problem: I need to insert 'upload' at a specific 'ID' into my table. It should make something like this:
insert into PHP_Project() where ID = ;
$pdo = new PDO($this->dsn, $this->username, $this->password, $this->pdoAttributes);
$statement = $pdo->prepare('insert into PHP_Project(upload) where ID = ? values (?,?)');
$statement->bindParam(1, $filename);
$statement->bindParam(2, $projectID);
$statement->execute();
I hope somebody can help me. Thanks in advance!!
The MYSQL query you wrote is incorrect. You need the MYSQL UPDATE query for updating the value at a specific column.
$statement = $pdo->prepare('UPDATE PHP_Project SET upload = ? WHERE ID = ?');
Check out this tutorial Mysql update tutorial

How to make sure script executes completely before executing?

I have a script which is containing some queries:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
As you see there is two statements (insert and update). All I'm trying to do is making sure both of them work or none of them.
I mean I want to implement a dependency between those two statements. If updating fails, then inserting shouldn't work and vice versa. How can I do that?
You could use sql transactions
http://www.sqlteam.com/article/introduction-to-transactions
You can use transactions and PDO has an api for this (http://php.net/manual/en/pdo.begintransaction.php),
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
As others said, you could use 'transactions'.
Or
you could mannualy check whether the data is right in the database. Just 'select' what you have inserted.
The 'execute' function return 'true' on success or 'false' on failure. You can do something like:
$isDone=$stm1->execute(array($value));
if(!$isDone){
echo 'Operation fails, I will stop.';
return false;
}

Getting the id of the last inserted record from an MSSQL table using PDO and PHP

I am trying to get the id of the last record inserted in an mssql database using pdo via php. I HAVE read many posts, but still can't get this simple example to work, so I am turning to you. Many of the previous answers only give the SQL code, but don't explain how to incorporate that into the PHP. I honestly don't think this is a duplicate. The basic insert code is:
$CustID = "a123";
$Name="James"
$stmt = "
INSERT INTO OrderHeader (
CustID,
Name
) VALUES (
:CustID,
:Name
)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
I have to use PDO querying an MSSQL database. Unfortunately, the driver does not support the lastinsertid() function with this database. I've read some solutions, but need more help in getting them to work.
One post here suggests using SELECT SCOPE_IDENTITY(), but does not give an example of how incorporate this into the basic insert code above. Another user suggested:
$temp = $stmt->fetch(PDO::FETCH_ASSOC);
But, that didn't yield any result.
If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this:
$CustID = "a123";
$Name="James"
$stmt = "INSERT INTO OrderHeader (CustID, Name)
OUTPUT INSERTED.id
VALUES (:CustID, :Name)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result["id"]; //This is the last inserted id returned by the insert query
Read more at:
https://msdn.microsoft.com/en-us/library/ms177564.aspx
http://php.net/manual/es/pdo.lastinsertid.php

Categories