mysql update not working.. needs help on update code - php

I'm using $_POST to data to my php page to update the mysql database. I'm trying to use the customer id to pick the row and update the company name and fname(firstname). When I figure this out, I'll add the rest to be updated. I've also included what I've tried via the "//" Thank you
-----dbconnect-----
$id= $_POST['id'];
$company= $_POST['company'];
$fname = $_POST['fname'];
echo $id;
echo $company;
echo $fname;
//$sql = mysqli_query($con,"UPDATE customer SET company = $company WHERE id= '.$id.'")
//$sql = "UPDATE customer SET company ='".mysql_real_escape_string($_POST['company'])."WHERE id='".mysql_real_escape_string($_POST['id'])."'";
$sql = "UPDATE customer SET company = $company WHERE id= '1'";
mysqli_select_db('customer');
$retval = mysqli_query( $sql, $con );
if(! $retval )
{
die('Could not update data: ' . mysqli_error());
}
echo "Updated data successfully\n";
mysqli_close($conn);
}

Making a few assumptions here but try this out...
// make mysqli throw exceptions on error
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// assuming your connection looks something like this
// you can pass the database name as the fourth argument instead of using select_db()
$con = new mysqli('localhost', 'user', 'pass', 'customer');
// $id = $_POST['id'], etc
// use a prepared statement with parameter placeholders.
// for more info see http://php.net/manual/mysqli.quickstart.prepared-statements.php
$stmt = $con->prepare('UPDATE customer SET company = ? WHERE id = ?');
// bind parameter variables and execute
$stmt->bind_param('si', $company, $id);
$stmt->execute();
echo 'Updated data successfully', PHP_EOL;

Related

PHP - open page base on id

I am trying to open one page base on id from web address.
My address is …/customer-single.php?id=5
And my code is:
try {
$connection = new PDO($dsn, $username, $password, $options);
$CustomerID = $_GET['CustomerID'];
$sql = "SELECT * FROM tblcustomer WHERE CustomerID = :CustomerID";
$statement = $connection->prepare($sql);
$statement->bindValue(':CustomerID', $CustomerID);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
So I need to see only result from CustomerID=5.
Change the following line
$CustomerID = $_GET['CustomerID'];
into
$CustomerID = $_GET['id'];
Because you need to specify the name of the parameter you have used in the url.
$CustomerID = $_GET['CustomerID'];
change this into this
$CustomerID = $_GET['id'];
in here what you have done is trying to access a php GET variable using a unidentified reference. in get request you send your parameter like this ?id=5
but when you access it, you try to access it in a wrong way . So what should actually happen is in order to access that GET variable you should reference it correctly like I have shown above

No Update done with PDO php

I have problem without any error in my code that update row ..
if(!isset($error)){
try {
$sql = "UPDATE `invoice` SET `client`='".$client."', `company`='".$company."' , `clientemail`='".$clientemail."' , `mobailclient`='".$mobailclient."' , `startdate`='".$startdate."' , `enddate`='".$enddate."' WHERE `id` ='".$id."'";
$count = $db->exec($sql);
//redirect to invoice page
header('Location: invoice.php');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
This is my code , i try to get variable $sql and go to mysql phpmyadmin and its work good ,, but in file not work and i dont get any error
==== Update ====
i try this and not work
try {
$sql = 'UPDATE invoice SET client = :client, company = :company, clientemail = :clientemail, mobailclient = :mobailclient, startdate = :startdate, enddate = :enddate WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(":client", $client);
$statement->bindParam(":company", $company);
$statement->bindParam(":clientemail", $clientemail);
$statement->bindParam(":mobailclient", $mobailclient);
$statement->bindParam(":startdate", $startdate);
$statement->bindParam(":enddate", $enddate);
$statement->bindParam(":id", intval($_GET['id']) );
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "<script>alert('".$statement->rowCount()."')</script>";
}
else
{
echo "<script>alert('No record updated')</script>";
}
Your query is opened for SQL Injection. You should use parameterized query which provide a kind of protection against SQL injection but will not provide 100% of protection. Kindly visit this Post for more details.
Try the following code by replacing table and column names.
$client = "my name";
$company = "my-company";
$id= 2;//make sure your table has a record with that specific id
$sql = 'UPDATE invoice SET client = :client, company = :company WHERE id = :id'; // here i am updating only two columns
//You can add more column that you want to upate like ColumnName = :ParameterIdentifier
//Where ParameterIdentifier Is the name of parameter used in bindParam as in my example company
$statement = $db->prepare($sql);
$statement->bindParam("client", $client); //Binding parameter for client
$statement->bindParam("company", $company); //Binding parameter for company
$statement->bindParam("id", $id);
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "Record updated successfully";
}
else
{
echo "No record updated";
}

Cannot Create Database PHP

I am beginning to create my own Interface to use with MySql though I cannot seem to create a database with the code I have at the bottom. Everything else works also i can echo out the $ObtainDatabase variable to see that it does have a value stored. Any suggestions would be great.
<?php
session_start();
//define connection
$conn = new mysqli('localhost', 'over_watch','XXXXXXx','billing');
//Variables
$UserEmail = $_SESSION['email'];
$MysqlUserDataBaseCreate = $_POST['create_database'];
//CheckIfUserExists
$SeeIfUserExist = $conn->prepare("SELECT (email) FROM database_users WHERE email= ?;");
$SeeIfUserExist->bind_param('s',$UserEmail);
$SeeIfUserExist->execute();
$SeeIfUserExist->bind_result($ObtainedEmail);
$SeeIfUserExist->store_result();
$SeeIfUserExist->fetch();
$RowsReturnedFromPreparedStatment = $SeeIfUserExist->num_rows();
if($RowsReturnedFromPreparedStatment < 1){
$InsertIntoDatabase = $conn->prepare("INSERT INTO database_users(email,check_if_created) VALUES(?,?);");
$InsertIntoDatabase->bind_param('ss',$UserEmail,$MysqlUserDataBaseCreate);
$InsertIntoDatabase->execute();
$SelectDatabaseToCreate = $conn->prepare(" SELECT (check_if_created) FROM database_users WHERE email = ?;");
$SelectDatabaseToCreate->bind_param('s', $UserEmail);
$SelectDatabaseToCreate->execute();
$SelectDatabaseToCreate->bind_result($ObtainDatabase);
$SelectDatabaseToCreate->fetch();
$CreateDatabase = "CREATE DATABASE $ObtainDatabase ;";
$conn->query($CreateDatabase);
}else{
echo 'user permitted to one database';
}
?>
Can you try this Code.
Details about this error can be found in the mysql docs. Reading those details makes it clear that the result sets of a prepared statement execution need to be fetched completely before executing another prepared statement on the same connection.
Here is the doc where you can refer
<?php
session_start();
//define connection
$conn = new mysqli('localhost', 'over_watch','XXXXXXx','billing');
//Variables
$UserEmail = $_SESSION['email'];
$MysqlUserDataBaseCreate = $_POST['create_database'];
//CheckIfUserExists
$SeeIfUserExist = $conn->prepare("SELECT (email) FROM database_users WHERE email= ?;");
$SeeIfUserExist->bind_param('s',$UserEmail);
$SeeIfUserExist->execute();
$SeeIfUserExist->store_result();
$SeeIfUserExist->bind_result($ObtainedEmail);
$SeeIfUserExist->store_result();
$SeeIfUserExist->fetch();
$RowsReturnedFromPreparedStatment = $SeeIfUserExist->num_rows();
if($RowsReturnedFromPreparedStatment < 1){
$InsertIntoDatabase = $conn->prepare("INSERT INTO database_users(email,check_if_created) VALUES(?,?);");
$InsertIntoDatabase->bind_param('ss',$UserEmail,$MysqlUserDataBaseCreate);
$InsertIntoDatabase->execute();
$InsertIntoDatabase->store_result();
$SelectDatabaseToCreate = $conn->prepare(" SELECT (check_if_created) FROM database_users WHERE email = ?;");
$SelectDatabaseToCreate->bind_param('s', $UserEmail);
$SelectDatabaseToCreate->execute();
$SelectDatabaseToCreate->store_result();
$SelectDatabaseToCreate->bind_result($ObtainDatabase);
$SelectDatabaseToCreate->fetch();
$CreateDatabase = "CREATE DATABASE $ObtainDatabase ;";
$conn->query($CreateDatabase);
}else{
echo 'user permitted to one database';
}
?>

Updating database using dropdown without using a submit button

I'm trying to update the table status value whenever I make a selection from the dropdown list.
The problem is I'm having a syntax error on my update query. I've read stuff about syntax error and I can't quite understand it. I think I'm gonna need a more specific help. Here's what I've done:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "companydb";
try
{
$conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["status"]))
{
$query = "UPDATE tickets SET status = '$status' WHERE id = $id";
$statement = $conn->prepare($query);
$statement->execute(array('status' => $_POST["status"]));
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
else
{
echo "unknown index: 'status'";
}
}
catch(PDOException $error)
{
echo $error->getMessage();
}
?>
And here's my table schema:
You are not performing prepared statements properly. You need to add the placeholder in the query and not the variables. The variables should be added in the execute() line.
$query = "UPDATE tickets SET `status` = :status WHERE `id` = :id";
$statement = $conn->prepare($query);
$statement->execute(array(':status' => $_POST["status"],':id' => $id));
Also FYI, $id is undefined.
Try Changing this:
$query = "UPDATE tickets SET status = $status WHERE id = $id";

Connect to Multiple Databases using MySQLi

I need to connect to two databases using PHP and use the results from the first query to get the rest of the data I need out of a second database.
So for the second connection, I need to connect to the second database and Select state and zipcode where the results from connection 1 (client) is equal to the firstname in database 2. How would I do this?
<?php
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['cd']) && is_numeric($_GET['cd'])) {
// get id value
$id = intval($_GET['cd']);
}
$results = $id;
//Open a new connection to the MySQL server
require "calendarconnect.php";
//chained PHP functions
$client = $mysqli->query("SELECT client FROM appointments WHERE ID = $results")->fetch_object()->client;
print $client; //output value
$mysqli->close();
Connection To Database Code is similar to the below
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some database','some password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
This isn't tested, but I think it would go something like this.
<?php
$dbc1 = new MySQLi()or die('error connecting to database');
$dbc2 = new MySQLi()or die('error connecting to database');
//build query 1
$query1 = "SELECT * FROM Table";
$result1 = $dbc1->query($query) or die("Error in query");
$thing1 = '';
// check result
if($result1->num_rows){
//fetch result as object
$row = $result1->fetch_object();
//set attributes
$thing1 = $row->Name;
}
//build query 2
$query2 = "SELECT * FROM AnotherTable WHERE Id = '$thing1'";
$result2 = $dbc2->query($query) or die("Error in query");
$thing2 = '';
// check result
if($result2->num_rows){
//fetch result as object
$row = $result2->fetch_object();
//set attributes
$thing2 = $row->Name;
}
?>
You would need to make 2 different connections
<?php
$mysqliDB1 = new mysqli('localhost', 'DB1UserId', 'pwd', 'db1');
$mysqliDB2 = new mysqli('localhost', 'DB2UserId', 'pwd', 'db2');
Now when you use the $mysqliDB1->.... you are talking to the DB1 database and when you use the $mysqliDB2->.... you are talking to the DB2 database
So
$client = $mysqliDB1->query("SELECT client FROM appointments WHERE ID = $results")
->fetch_object();
$locn = $mysqliDB2->query("SELECT state,zipcode
FROM location
WHERE ClientID = {$client->FirstName}")
->fetch_object();
echo $locn->state;
echo $locn->zipcode;
I am guessing the table name and so on, but I am not clarevoyant so you will have to fill that in for yourself.
If you want to perform queries in two databases at the same time you need to have two separate mysqli objects. To open the connection you can use the following code:
// Don't forget to enable error reporting!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db1 = new mysqli('localhost', 'user', 'pass', 'dbName');
$db1->set_charset('utf8mb4'); // always set the charset
$db2 = new mysqli('localhost', 'user', 'pass', 'dbName2');
$db2->set_charset('utf8mb4'); // always set the charset
Then you can perform your two statements in each database separately.
// get id value
$id = intval($_GET['cd']);
// Get client name from DB1
$stmt = $db1->prepare('SELECT client FROM appointments WHERE ID = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$client = $stmt->get_result()->fetch_object();
// Get state and zipcode from DB2
$stmt = $db2->prepare('SELECT state,zipcode FROM location WHERE ClientName = ?');
$stmt->bind_param('s', $client->client);
$stmt->execute();
$location = $stmt->get_result()->fetch_object();
echo $location->state;
echo $location->zipcode;

Categories