Can't seem to get the database to update. No errors are returned, all variables are being passed into the function and I've googled for hours probably even days. What's weird is that I have another function using the same code that's in this function that works fine...
public function updateCustomer($uname, $umail, $ushipping, $uchargeID, $udate, $ID)
{
try {
$dbhost = 'host';
$dbuser = 'app';
$db_name = 'order';
$dbpass = '';
$conn1 = mysql_connect($dbhost, $dbuser, $dbpass);
$sql1 = "UPDATE customers
SET name = $uname, email = $umail, shipping = $ushipping, shipped = 'NO', charge_ID = $uchargeID, date = $udate
WHERE ID = $ID";
mysql_select_db('orders');
mysql_query($sql1);
return ;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
As I mentioned in my comment above, mysql_query() will not throw any exception. You should check it's return value, and if false, echo out mysql_error(). The issue you're having most likely is because none of your variables are being escaped in the database. This is not valid syntax:
UPDATE customers SET name = example_username
You want this:
UPDATE customers SET name = 'example_username'
You're much better off to just tell MySQL where you want variables, and let MySQL to the magic using prepared statements. An example can be found here:
public function updateCustomer($uname, $umail, $ushipping, $uchargeID, $udate, $ID)
{
try {
$dbhost = 'host';
$dbuser = 'app';
$db_name = 'order';
$dbpass = '';
$db = new PDO("mysql:host={$dbhost};dbname={$db_name}", $dbuser, $dbpass);
$sql1 = "UPDATE customers
SET name = :uname, email = :umail, shipping = :ushipping, shipped = 'NO', charge_ID = :ucharge_id, date = :udate
WHERE ID = :id";
$stmt = $db->prepare($sql1);
$res = $stmt->execute([
'uname' => $uname,
'umail' => $umail,
'ushipping' => $ushipping,
'ucharge_id' => $uchargeID,
'udate' => $udate,
'id' => $ID
]);
return;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
Related
I have the codes following for a delete process;
if(isset($_POST['deleteSong'])) {
$id = $_POST['deleteSong'];
$delete = $connect->prepare('DELETE FROM lyrica_songs WHERE id = ?');
$delete->execute(array($id));
$error = TRUE;
}
These codes is not deleting row. I have 7 columns at lyrica_songs and 3 of them are integers. ID (auto increment), song_singer_id and song_hit and when i run my codes ID, song_singer_id, song_hit are not deleted. I tried making them text instead integers and ID and song_hit still can't be deleted.
EDIT:
My connection code
<?php
$db_host = 'mysql:host=localhost;dbname=lyrica;charset=utf8';
$db_username = 'root';
$db_password = '';
try {
$connect = new PDO($db_host,$db_username,$db_password);
$connect->exec('SET NAMES UTF-8; SET CHARACTER SET UTF-8');
} catch (PDOException $error) {
echo "Veritabanı bağlantısı kurulamadı: " . $error->getMessage();
}
PDO version of #ChukwuemekaInya code
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
try {
$query = "DELETE FROM `lyrica_songs` WHERE `id`=:id ";
$dB = new PDO("mysql:host=$db_host;dbname=lyrica", $db_username, $db_password);
$stmt = $dB->prepare($query);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
return $stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
try {
$connect = new PDO("mysql:host=$db_host;dbname=lyrica",$db_username,$db_password);
} catch (PDOException $error) {
echo "Veritabanı bağlantısı kurulamadı: " . $error->getMessage();
}
$delete = $connect->prepare('DELETE FROM lyrica_songs WHERE id = :id');
$delete->bindParam(':id', $id);
$delete->execute();
$delete->close();
<?php
require 'functions/connection.php';
$conn = Connect();
$e_id = $conn->real_escape_string($_POST['e_id']);
$first_name = $conn->real_escape_string($_POST['first_name']);
$last_name = $conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->real_escape_string($_POST['e_department']);
$sql = "UPDATE employee SET firstname='$first_name' WHERE id=$e_id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
I'm trying to use the first_name variable inside the update query.
I tried echo the variable and its working...
this is my connection code that im using.
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "company";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
if i i replace the variable with anything between "" the database is getting updated
I'd suggest making it more secure and using prepared statements. This is an example using mysqli, but I prefer PDO:
<?php
require 'functions/connection.php';
$conn = Connect();
// Prepare the query
$myQuery = $conn->prepare("UPDATE employee SET firstname=? WHERE id=?");
$e_id = $conn->real_escape_string($_POST['e_id']);
$first_name = $conn->real_escape_string($_POST['first_name']);
$last_name = $conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->real_escape_string($_POST['e_department']);
// Bind your variables to the placemarkers (string, integer)
$myQuery->bind_param('si', $first_name, $e_id);
if ($myQuery->execute() == false) {
echo 'Error updating record: ' . $mysqli->error;
}
else {
echo 'Record updated successfully';
}
$myQuery->close();
?>
Note: The 'cleansing' you're doing in the middle I have left, but it's not really necessary with prepared statements.
functions/connection.php (Now an object):
<?php
class Connect
{
private $dbhost = "localhost";
private $dbuser = "root";
private $dbpass = "";
private $dbname = "company";
public $conn;
public function __construct()
{
if($this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname))
{
//connection established
//do whatever you want here
}
else
{
//Error occurred
die($this->conn->error);
}
}
//other functions here
}
?>
Change mysqli_query to: $conn->conn->query($sql);
Prepared statement:
Avoid SQLI injection
if($stmt = $conn->conn->prepare("UPDATE employee SET firstname = ? WHERE id = ?"))
{
$stmt->bind_param('si', $first_name, $e_id);
$stmt->execute();
echo $stmt->affected_rows;
}
Final code:
<?php
require 'functions/connection.php';
$conn = new Connect();
$e_id = $conn->conn->real_escape_string($_POST['e_id']);
$first_name = $conn->conn->real_escape_string($_POST['first_name']);
$last_name = $conn->conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->conn->real_escape_string($_POST['e_department']);
if($stmt = $conn->conn->prepare("UPDATE employee SET firstname = ? WHERE id = ?"))
{
$stmt->bind_param('si', $first_name, $e_id);
$stmt->execute();
echo $stmt->affected_rows;
}
$conn->conn->close();
?>
I am getting
Fatal error: Call to a member function query() on a non-object in
C:...\test.php on line 27
after calling callQuery2.
<?php
dbConnect();
callQuery1();
callQuery2();
function callQuery1(){
// SQL query
$q = "SELECT * FROM table1 WHERE name like 'john%' ";
// Execute query
$data1 = exeQuery($q);
}
function callQuery2(){
// SQL query
$q = "SELECT * FROM table2 WHERE event = 'holiday' ";
// Execute query
$data2 = exeQuery($q);
}
// Execute SQL Query
function exeQuery($qry) {
global $pdo;
####### LINE 27 #######
$stmt = $pdo->query($qry);
if($stmt = $pdo->prepare($qry)) {
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
}
// database connection
function dbConnect(){
$DBSERVER = "***";
$DBUSER = "***";
$DBPASS = "***";
$DBNAME = "***";
// OBDC
try {
$pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex) {
//die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
?>
Why the error only appears after at that time?
Is the a better way to do this?
Regards,
Elio Fernandes
This would be better encapsulated without the global $pdo; part. Instead return the PDO object from your connect method, and pass it to the others, to be used.
N.B. I've deliberately given the variables different names in different places, to illustrate that the name doesn't have to be the same when it's passed from one scope to another, it's the object that's passed which is important. You might perhaps consider using consistent names though, to make it easier to comprehend the code later, and trace the object through the flow.
<?php
$dbConn = dbConnect();
callQuery1($dbConn);
callQuery2($dbConn);
function callQuery1($db){
// SQL query
$q = "SELECT * FROM table1 WHERE name like 'john%' ";
// Execute query
$data1 = exeQuery($q, $db);
}
function callQuery2($db){
// SQL query
$q = "SELECT * FROM table2 WHERE event = 'holiday' ";
// Execute query
$data2 = exeQuery($q, $db);
}
// Execute SQL Query
function exeQuery($qry, $pdo) {
####### LINE 27 #######
$stmt = $pdo->query($qry);
if($stmt = $pdo->prepare($qry)) {
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
}
// database connection
function dbConnect(){
$DBSERVER = "***";
$DBUSER = "***";
$DBPASS = "***";
$DBNAME = "***";
// OBDC
try {
$pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
catch(PDOException $ex) {
//die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
?>
What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();
I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.