I just transfered my website to another hosting, but some scripts stop working, many very simple as this:
mysql_query("INSERT INTO orders (userid,cid,tipou,cantidad,factura,producto,lote,notas,cprod,pbase,cenvio,fecha,status,cobro,ip)
VALUES ('{$_SESSION['id_usuario']}','{$cid}','{$tipou}','{$cantidad}','{$factura}','{$producto}','{$numlot}','{$notas}','{$cprod}','{$pbase}','{$cenvio}','{$fecha}','{$status}','{$cobro}','{$ip}')");
Im using php version 5.6, And tryed to enable Error Reporting, but I dont got any warnings, the query don't INSERT any data on the table.
Please apologize my english, and thanks for helping.
This is how i set it up pretty much:
connect.php:
<?php
define('DB_HOSTNAME', 'HOSTNAME');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE');
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host='.DB_HOSTNAME.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step to close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
?>
Then i just use functions to do the work:
<?php
function functionNameHere() {
$query = "INSERT INTO orders (userid,cid,tipou,cantidad,factura,producto,lote,notas,cprod,pbase,cenvio,fecha,status,cobro,ip) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$params = array($_SESSION['id_usuario'],etc...);
dataQuery($query,$params);
}
?>
then just call <?php functionNameHere(); ?>
Created this:
$sessid = $_SESSION['id_usuario'];
if (!$mysqli->query("INSERT INTO orders (userid,cid,tipou,cantidad,factura,producto,lote,notas,cprod,pbase,cenvio,fecha,status,cobro,ip)
VALUES ('".$sessid."','".$cid."','".$tipou."','".$cantidad."','".$factura."','".$producto."','".$numlot."','".$notas."','".$cprod."','".$pbase."','".$cenvio."','".$fecha."','".$status."','".$cobro."','".$ip."')")) {
echo "Falló la Insersión de Datos: (" . $mysqli->errno . ") " . $mysqli->error;
} else {echo"Datos Insertados";}
Working on localhost, but not in my server.
Related
Please help with this difficult to understand bug: php always execute sql update inside IF with $_POST in condition.
When condition is false: the code i) not executes the echo command, but ii) it still executes the sql command
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
and the strange thing is that, if I try the iF condition with "IF (1 ==2)" then code works well. In other words, it does not execute the sql.
The full code
<html>
<body>
<?php
$servername = "localhost";
$username = "reviinve_vchain";
$password = "";
var_dump($_POST["scanned_set"]);
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Retrieve data from db
$sql = "SELECT * FROM `id_scan` WHERE `id` = 1";
foreach ($conn->query($sql) as $row) {
echo "print scan number after retrieving statement ".$row['scan_count'] . "\t";
// print $row['color'] . "\t";
$count_update = $row['scan_count'] + 1;
}
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update count number to db
echo 'new count number' . $count_update;
$sql = "UPDATE `id_scan` SET `scan_count` = $count_update WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
?>
</body>
</html>
Try scrubbing your request variable first:
$do_update = !(trim(strtolower($_REQUEST["scanned_set"])) == "saved")
if ($do_update) {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
This is my code:
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
?>
But, when I run it, nothing gets printed. What's wrong?
Yes, my table is not empty. I am 100% able select & print data using MySQLi Object-oriented, but not working with PDO. What's wrong in my code?
Call the function
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
//call the function here
printResult($conn);
?>
To run a function you must call it.
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
// and if this fails there is no point continuing so add an exit
exit;
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
printResult($conn); // call the function
?>
You don't call function printResult from anywhere.
Add to your code printResult($conn);
I previously used mysqli and now i would like to use PDO instead but I did not echo any result from my database. I have read so many articles about PDO tutorial but they teach different things. I tried to pick piece by piece and came up with this code, but i did not echo any result from my database or throw any error.
try{
$stmt = $conn->query("SELECT * FROM memberpost ORDER BY poststart DESC LIMIT $start_from,$num_rec_per_page");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
if(count($row)>0){
while($row = $stmt->fetch()) {
echo $row['title']."<br>";
}
}
else{
echo "NO result found";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Here is my database connect code:
try {
$conn = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', $username, $password); //new PDO
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Edit your database connection code to this:
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
And try this code in your .php file :
$sth = $conn->prepare(SELECT * FROM memberpost)
$sth->execute();
$red = $sth->fetchAll();
print_r($red);
I found this on the internet, it might help:
// defining query
$sql = 'SELECT name, surname, zip FROM table';
// showing results
foreach($db->query($sql) as $row){
echo $row['name']. '<br>';
echo $row['surname']. '<br>';
echo $row['zip']. '<br>';
}
Source (ita): http://www.mrwebmaster.it/php/guida-utilizzo-pdo_7594_4.html
I want to delete a row from a table using php pdo.I am using the following code,
$dsn = 'mysql:host=127.0.0.1;dbname=as1';
$user = 'root';
$password = '';
try {
// Connect and create the PDO object
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'Database connection failed - ';
echo $e->getMessage();
exit;
}
$sql1="DELETE FROM photo WHERE id=?";
$q1=array($result);
try {
$stmt1 = $pdo->prepare($sql1);
$stmt1->execute($q1);
$stmt1->setFetchMode(PDO::FETCH_BOTH);
$result1= $stmt1->fetchColumn();
}
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
But my datas in a table are not deleting ...It shows failed to run query..
You did not provide a value for ?
$stmt1->execute($q); // Where is $q defined?
Should be something like
$q=array(1);
$stmt1->execute($q);
I'm trying out the PDO extension, and was wondering if it were possible to store the opening of the DB connection as a function that could be called whenever needed. I tried some basic stuff, but it doesn't seem to work. Can it?
Example Function
function DB() {
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$conn) {
echo "<br />MySQL SERVER CONNECTION ERROR.<br />\n";
}
if($conn) {
return $conn;
}
}
Example Useage
function is_post_id($submitted) {
try {
$id = $submitted;
DB();
//check to see if there is a post
//with an id matching the submitted query
$qPOST= $conn->prepare('SELECT COUNT(*) FROM posts WHERE id = :id');
$qPOST->execute(array('id' => $id));
//results counted
$cPOST= (int)$qPOST->fetchColumn();
if($cPOST > 0) {
return TRUE;
}
else {
return FALSE;
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
call it as :
$conn = $this->DB();
OR
$conn = $className->DB();