PDO UPDATE query doesn't actually update records - php

This is my code. I created a code that was a update of news
But at moment not show errors. But does not make a update....
<?php
require("common.php");
global $host, $dbname, $username, $password, $options;
$conteudox = $_POST['conteudo'];
//$imagem = $_['imagem'];
if(isset($_POST['conteudo']))
{
$dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password);
$sql = "UPDATE news SET conteudo = '{$conteudox}' WHERE id = '{$id_cont}'";
$count = $dbh->exec($sql);
echo "ssssss";
$dbh = null;
}
else
{
echo "nnnnn";
}
?>

try again with
if(isset($_POST['conteudo']))
{
$dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("UPDATE news SET conteudo = ? WHERE id = ?");
// where's $id_cont comming from?
$count = $stmt->execute(array($_POST['conteudo'],$id_cont));
echo "ssssss";
$dbh = null;
}
else
{
echo "nnnnn";
}

Check all your variables and try to use :
$sql = "UPDATE news SET conteudo = :conteudox WHERE id = :id_cont";
$dbh->prepare($sql);
$count=$dbh->execute(array(':conteudox'=>$conteudox,
':id_cont'=>$id_cont));

Related

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

Putting checkbox inputs into a MySQL table column with PHP

<?php
session_start();
$servername = "localhost";
$username = "_admin";
$password = "";
$dbname = "_users";
$value = $_POST['userTel'];
$sesh = $_SESSION['userSession'];
$checkbox1=$_POST['site'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1.",";
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// begin the transaction
$conn->beginTransaction();
// our SQL statements
$conn->exec("UPDATE tbl_users SET userTel = '$value' WHERE userID = '$sesh'");
$conn->exec("UPDATE tbl_sites SET siteName ('$chk')");
// commit the transaction
$conn->commit();
echo "all's good ^.^";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
That's my code, and this is the error that's returned to me:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '('kith,')' at line 1
(kith is 1 of the input values)
What am I doing wrong here?
A more traditional prepared stmt possible way ?
session_start();
$servername = "localhost";
$username = "_admin";
$password = "";
$dbname = "_users";
$value = $_POST['userTel'];
$sesh = $_SESSION['userSession'];
$checkbox1 = $_POST['site'];
$chk = "";
foreach ($checkbox1 as $chk1) {
$chk .= $chk1 . ",";
}
/* making sure there not the last , anyway */
$chk = rtrim($chk, ",");
/* setting conn */
try {
$conn = new PDO('mysql:host=' . $servername . ';dbname=' . $dbname . ';charset=UTF8', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
/* prepared stmts */
$sql1 = "UPDATE tbl_users SET userTel = ? WHERE userID = ?";
$sql2 = "UPDATE tbl_sites SET siteName = ?";
$stmt1 = $conn->prepare($sql1);
$stmt2 = $conn->prepare($sql2);
/* bindings */
$stmt1->bindParam(1, $value, PDO::PARAM_STR);
$stmt1->bindParam(2, $sesh, PDO::PARAM_STR);
$stmt2->bindParam(1, $chk, PDO::PARAM_STR);
/*exec*/
$sql1->execute();
$sql2->execute();
You have to remove tha last , from $chk.
Try this.
if(strlen($chk)>0){
substr($chk, 0, strlen($chk)-1);
}

How to get count using prepared statment in PHP?

$con = mysqli_connect("localhost","root","","uploads");
if($con)
{
$sql = "SELECT COUNT(id) FROM products";
$obj = mysqli_query($con,$sql);
if(is_object($obj))
{
$rows = mysqli_fetch_row($obj);
$totalrows = $rows[0];
enter code here
}else{
echo "not object";
}
}else
{
echo "db issue";
}
This code is perfectly fine but i want to perform same operation using prepared statment.i have tried but could't get the same result using prepared statment. what i have to do?
Check out the following solutions
//db configuration
$server = 'localhost';
$dataBase = 'uploads';
$UserName = 'root';
$Password = '';
PHP MySQLi Prepared Statement
$con = mysqli_connect($server, $userName, $password, $dataBase);
$sql = "SELECT COUNT(id) FROM products";
$stmt = mysqli_prepare($con, $sql);
if(mysqli_stmt_execute($stmt)) {
mysqli_stmt_bind_result($stmt, $totalRows);
mysqli_stmt_fetch($stmt);
echo $totalRows;
}
PHP MySQLi Object-oriented
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->query("SELECT COUNT(id) FROM products");
if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_row()) {
$totalRows = $row[0];
echo 'Total number of rows is '.$totalRows;
}
}
$stmt->close();
PHP MySQLi with Object-oriented Prepared Statement
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
echo 'Total number of rows is '.$totalRows;
$stmt->close();
PHP PDO with Prepared Statement
try {
$con = new PDO("mysql:host=$server;dbname=$dataBase;", $userName, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$totalRows = $stmt->fetchColumn();
echo 'Total number of rows is '.$totalRows;
} catch(PDOException $e){
echo $e->getMessage();
die();
}

How to CRUD using PDO Connection?

I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.
Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");
Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}

Login script using PDO extension not working

I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>

Categories