Using isset for correction? - php

I'm new to PHP,I got error in my web page.It said:
Notice: Undefined index: itemid in /home/tz005/public_html/COMP1687/edit.php on line 103
Can I use isset to fix this problem? If yes, how to do so? Here is my script:
<?php
//include database connection
include 'dbconnect.php';
// if the form was submitted/posted, update the item
if($_POST){
//write query
$sql = "UPDATE
item_information
SET
itemtitle = ?,
itemdescription = ?,
date = ?,
WHERE
itemid= ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(
'sssi',
$_POST['itemtitle'],
$_POST['itemdescription'],
$_POST['date'],
$_POST['itemid']
);
// execute the update statement
if($stmt->execute()){
echo "Item was updated.";
// close the prepared statement
$stmt->close();
}else{
die("Unable to update.");
}
}
$sql = "SELECT
itemid, itemtitle, itemdescription, date
FROM
item_information
WHERE
id = \"" . $mysqli->real_escape_string($_GET['itemid']) . "\"
LIMIT
0,1";
// execute the sql query
$result = $mysqli->query( $sql );
//get the result
if ($result = $mysqli->query( $sql )) {
if ($row = $result->fetch_assoc()) {
// $row contains data
}
}
//disconnect from database
$result->free();
$mysqli->close();
?>

change
$mysqli->real_escape_string($_GET['itemid'])
to
$mysqli->real_escape_string($_POST['itemid'])
or use empty() or isset() to check values exist

Yes you can do it with isset() function
Create conditions for it
if(isset($_GET['itemid'])){
//execute your code
}
else{
//header them back to page or show error that itemid not set or something else whatever suits you
}

Related

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";
}

getting session into each page

i want to insert into a table depending on the id of the session:
here the code in class.php:
public function activate($activation, $id,$change,$userID){
$stm1= $this->conn->prepare("INSERT INTO `log` (`date`,`change`) VALUES(CURRENT_TIMESTAMP(),'$change') WHERE `user_id` =$userID");
($stm1->execute());
$stmt = $this->conn->prepare("UPDATE `segments` SET `activation` = '$activation' WHERE `id` = '$id'")
or die($this->conn->error);
if ($stmt->execute()) {
$stmt->close();
$this->conn->close();
return TRUE;
}
}
at the top of the page i have this:
require './config.php';session_start();$userID = $_SESSION['user_id'];
and in action.php where the action go i have this:
$conn = new db_class();
$conn->activate($activation, $id,$change,$userID);
echo "Updated successfully.";
exit;
the first query insert into log is not working \ please help
This should be a comment but I don't have the rep yet...
Primarily, you don't do that type of insert with a WHERE clause. The insert will fail.
As an aside, that insert is open to sql injection. Bind your your parameters. Also, you should add error handling. If you had that, you would see the insert fails. Quick example (1 way...there are other ways...and I assumed $change is a string and $userId is an int...)
$sql = 'INSERT INTO log
SET `date` = CURRENT_TIMESTAMP(),
change = :change,
user_id = :user_id;';
$stmt = $this->conn->prepare( $sql );
$stmt->bindParam( ':change', $change, PDO::PARAM_STR );
$stmt->bindParam( ':user_id', $userID, PDO::PARAM_INT );
$result = $stmt->execute();
if (!$result) {
// failure -> get and handle the error
$error_array = $stmt->errorInfo();
} else {
// do something
}
The docs can help > pdo::execute, pdo::errorinfo

Why MySQLI prepare is failing but no errors is being reported

I am stuck up as to why my Update prepare statement is failing but though I do not see any SQL error:
<?php
include(dirname(__FILE__).'\config.php' );
$id = $_POST['id'] ;
$value = $_POST['value'] ;
$column = $_POST['columnName'] ;
$columnPosition = $_POST['columnPosition'] ;
$columnId = $_POST['columnId'] ;
$rowId = $_POST['rowId']
$response['status']='';
$mysqli = new mysqli($sql_details['host'],$sql_details['user'],$sql_details['pass'],$sql_details['db']);
$mysqli->autocommit(FALSE);
$stmt = $mysqli->stmt_init();
if ($stmt = $mysqli->prepare("UPDATE users SET ? = ? where id = ?")) {
$response['status']='OK';
//$stmt->bind_param("ssi", $column, $value, intval(ltrim(substr($id, -4),'0')));
//$stmt->execute();
//$response['status'] = $mysqli->affected_rows;
//if ($mysqli->affected_rows == 1 )
//$response['status'] = 'success';
$stmt->close();
//if (!$mysqli->commit())
//$response['status'] = 'fail';
$mysqli->close();
}
else
$response['status']=$mysqli->error;
}
echo json_encode($response);
?>
Even though I have commented most of the lines and expect to the conditional string 'OK' at my UI side - I never ever see that . No errors is also reported - what am I doing wrong?
It seems that the UPDATE prepared statement works fine when in case of column name is present rather than a bind value like the below one works:
if ($stmt = $mysqli->prepare("UPDATE users SET first_name = ? where id = ?"))
Is there any way to have it the way I have requested?

php script wont add record to mysql

The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this

Fatal error: Call to a member function execute() on a non-object

$sql = "UPDATE Student ".
"SET score = $total_score ".
"WHERE student_id = $student_id";
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$query = "SELECT faculty_id ".
"From Student s ".
"WHERE student_id =$student_id";
$state =$mysqli->prepare($query);
$state->execute();
$state->bind_result($faculty_id);
if ($state->fetch())
{if (strpos($faculty_id, '1') > 0) {
include ('./Registration_Step_3_Student.php');
} else
{
include ('./Registration_Step_3_Mentor.php');
}
}
So whenever i try to run my second query called $state, i get this error that states it cannot be execute. I am relatively new to SQL and PHP so any help would be appreciated. Thanks!
Since you are using mysqli you should learn how to bind properly, please read up on bind_Param
mysqli_stmt::prepare returns an false when failing, you should never execute the statement when it does:
$sql = "UPDATE Student SET score = ? WHERE student_id = ?";
$stmt = $mysqli->prepare($sql);
if($stmt){
$stmt->bind_param('si', $total_score, $student_id);
if($stmt->execute()){
$query = "SELECT faculty_id From `Student s` WHERE student_id = ?";
$state =$mysqli->prepare($query);
$stmt->bind_param('i', $student_id);
if($state->execute()){
var_dump($state->fetch());
}else{
echo 'SELECT failed';
printf("Error: %s.\n", $state->error);
}
}else{
echo 'failed to execute UPDATE';
}
}else{
echo 'failed to prepare() UPDATE \n';
printf("Error: %s.\n", $stmt->error);
}
Hope this helps

Categories