if (isset($_GET['edit'])) {
global $conn;
$stmt = mysqli_prepare($conn, "UPDATE orders SET customerTelephone='delivered' WHERE orderId=? ");
if (!$stmt){
echo "Error preparing statement: " . mysqli_error($conn);
exit;
}
if (!mysqli_stmt_bind_param($stmt, "i", $_POST['edit'])){
echo "Error binding parameters: " . mysqli_stmt_error($stmt);
exit;
}
if (!mysqli_stmt_execute($stmt)){
echo "Error executing statement: " . mysqli_stmt_error($stmt);
exit;
} else {
echo "Success! Order has been updated.";
}
} else {
echo "edit not set";
}
I have tried to check the query but found no issues, i need extra set of eyes on it. Help correct this code
Related
This is the code I'm using for deleting row from my DB:
<?php
$eid = $_GET['eid'];
$con = mysqli_connect("localhost", "root", "","project") or die("Connection failed");
echo "connection is done";
$query = "delete from exam where eid='$eid'";
if ($con->query($query)==TRUE)
{
echo " record deleted";
}
else
{
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
?>
The else statement is not getting executed. It displays "record deleted" for every value even if the value is not found in the database.
Why is this happening? how can I verify that my record has been deleted from my DB?
You can use mysqli.affected-rows.
Consider the following:
$query="delete from exam where eid='$eid'";
if ($con->query($query)==TRUE && $con->affected_rows > 0) {
echo " record deleted";
} else {
echo "Error: " . $query . "<br>" . $con->error;
}
i can't find the solution.
$prepStatement->execute(array_values($inv)); does not work
I got an error at this line.
my php script:
<?php
$response=array();
$json = $_REQUEST['json'];
$data = json_decode($json);
var_dump(json_decode($json, true));
print "Starting request". "<br/>";
if($_SERVER['REQUEST_METHOD'] == "POST" && (json_last_error() === JSON_ERROR_NONE))
{
if($data->connection && $data->wykazy)
{
print "connection and wykazy exist". "<br/>";
if ($data->connection->Host && $data->connection->db && $data->connection->User && $data->connection->password) {
print "connection Host, db, User, password are OK". "<br/>";
try
{
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbObj = new PDO('mysql:host='.$data->connection->Host.';dbname='.$data->connection->db, $data->connection->User, $data->connection->password, $opt);
print "Proba ustanowienia polaczenia! Bledy: " . $dbObj->errorCode() . "<br/>";
createWykaz($dbObj, $data);
}
catch (PDOException $e)
{
print "Blad podczas tworzeniu obiektu dbObj!: " . $e->getMessage() . "<br/>";
$response["success"]=0;
$response["message"]="Can not connect to database!: " . $e->getMessage();
echo json_encode($response);
die();
}
//$mysqli = new mysqli($data->connection->Host, $data->connection->User, $data->connection->password, $data->connection->db);
}
}
else
{
print "connection i wykazy nie istnieją! " . "<br/>";
$response["success"]=0;
$response["message"]="Error: Required fields are missing!";
echo json_encode($response);
}
}
function createWykaz($dbObj, $data)
{
try{
$allowedVariables = array(
'wyk_ilosc',
'wyk_czasod',
'wyk_czasdo',
'wyk_id_czynnosc',
'wyk_id_pracownik',
'wyk_id_partia',
'wyk_status',
);
$sql = "insert into wykaz (". implode(',', $allowedVariables) .")";
$sql.= " VALUES (". substr(str_repeat('?,', sizeof($allowedVariables)), 0, -1) .");";
print "sql: ". $sql . "<br/>";
if($prepStatement = $dbObj->prepare($sql)){
//edit
$dbObj->beginTransaction();
foreach ( $data->wykazy as $inv ) {
$res = $prepStatement->execute(array_values($inv));
}
/*
$prepStatement = $dbObj->prepare($sql)
foreach ($data->wykazy as $row) {
$dbObj->executeMultiple($prepStatement, $row);//return DB_OK
}
*/
$response["success"]=1;
$response["message"]="Wszystkie wykazy successfully added to Database!";
echo json_encode($response);
$dbObj->commit();
}
else {
$response["success"]=0;
$response["message"]="Błąd podczas przygotowania zapytania!"+ $prepStatement;
echo json_encode($response);
}
$dbObj=null;
$prepStatement=null;
}catch(PDOException $e){
//Error handling goes here
echo "Sorry, the website is experiencing problems.";
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $e->getMessage() . "\n";
$response["success"]=0;
$response["message"]="Our query failed to execute!". $e->getMessage();
echo json_encode($response);
$dbObj=null;
$prepStatement=null;
}
}
?>
it works till:
$prepStatement->execute(array_values($inv));
I am getting an error at this position, but $data->wykazy is an array.
I can change my code to:
$sth = $db->prepare('INSERT INTO numbers VALUES (?, ?, ?)');
foreach ($alldata as $row) {
$db->execute($sth, $row);
}
but I will try the other way.
Thanks for help
Sebastian
The output from Postman:
Postman part1
Postman part2
I got this error message, I was trying to update my entry through this link but this message came up:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ID='8'' at line 1
<?php
$validform = true;
$ID = $_GET['ID'];
if ($ID=="") {
echo "They didn't use GET. Are they POSTing anything? </br>";
$rid = $_POST['ID'];
if ($ID==''){
$validform = false;
} else {
echo "The user submitted a POST. Update Category ID: ". $ID . "<br />";
if (is_numeric($ID)) {
if ($ID<=0 or $ID > 2147482647) {
$validform = false;
$riderrormessage = 'The Category ID must be greater than zero and less than 2147482647.';
} else {
//it's okay
}
} else {
$validform = false;
$IDerrormessage = 'The Category ID must be an integer.';
}
//****************************************************
//Category
$Cat = htmlentities($_POST['Cat']);
if($Cat=='') {
$validform = false;
$Caterrormessage = 'Category is a required field.';
} else {
$emptyform = false;
if (strlen($Cat)>100) {
$validform = false;
$Caterrormessage = 'The Category must be less than 100 characters long.';
}
}
//*******************************************************
//Description
$Description = htmlentities($_POST['Description']);
if($Description=='') {
$validform = false;
$Descriptionerrormessage = 'Description is a required field.';
} else {
$emptyform = false;
if (strlen($Description)>900) {
$validform = false;
$Descriptionerrormessage = 'Your Description must be less than 900 characters long.';
}
}
//validation finished
if ($validform) {
echo "Going to update Category ID: ". $ID . "<br />";
echo "All data was valid.<br />";
echo "Connecting to database server.<br />";
try {
//variable stores the connection -> $conn
//PDO is a php data object -> helps prevent SQL injection
//host = Database server host name
//username = name of read/write user
//password = that user's password
$conn = new PDO("mysql:host=Database info);
} catch(PDOException $e) { //this should tell us if there was a connection problem
echo "Error connecting to server: " . $e->getMessage();
die;
}
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection to server succeeded.<br />";
echo "Connecting to database Category...<br />";
try {
//if executing a query, NO USER ENTERED fields should be in query string!
$conn->query("USE Database Table;");
} catch (PDOException $e) {
echo "Error connecting to database: " . $e->getMessage();
die;
}
echo "Connection to Category database succeeded.<br />";
echo "Preparing SQL statement.<br />";
//NO VARIABLES ALLOWED IN SQL
//ALL USER ENTERED VALUES are going to be parameters -> variable
names that start with a colon
$SQL = "UPDATE Category SET ID=:ID, Cat=:Cat,
Description=:Description";
$SQL .= " WHERE ID=:ID";
echo "This is the SQL statement: " . $SQL . "<br />";
echo "Preparing to update Category record. <br />";
try {
$sth = $conn->prepare($SQL);
$sth->bindParam(":ID", $ID);
$sth->bindParam(":Cat", $Cat);
$sth->bindParam(":Description", $Description);
$sth->execute();
} catch (PDOException $e) {
echo "Error adding Category record: " . $e->getMessage();
die;
}
echo "Record updated in database. <br />";
Header("Location: Header.php");
die;
}
}
} else if (!is_numeric($ID)) {
$validform = false;
}
echo "The user entered Category ID: ". $ID . "<br />";
echo "Connecting to database server.<br />";
try {
//variable stores the connection -> $conn
//PDO is a php data object -> helps prevent SQL injection
//host = Database server host name
//username = name of READ ONLY user
//password = that user's password
$conn = new PDO("mysql:host=Database Info);
} catch(PDOException $e) { //this should tell us if there was a connection problem
echo "Error connecting to server: " . $e->getMessage();
die;
}
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection to server succeeded.<br />";
echo "Connecting to database Category...<br />";
try {
//if executing a query, NO USER ENTERED fields should be in query string!
$conn->query("USE Database Table;");
} catch (PDOException $e) {
echo "Error connecting to database: " . $e->getMessage();
die;
}
echo "Connection to Category database succeeded.<br />";
//SQL statement will have user-entered data, so BIND needed
$SQL = "SELECT ID, Cat, Description";
$SQL .= "FROM Category WHERE ID=:ID;";
try {
$sth = $conn->prepare($SQL);
$sth->bindParam(":ID", $ID);
$sth->execute();
} catch (PDOException $e) {
echo "Error selecting Category records: " . $e->getMessage();
die;
}
echo "Query executed successfully. <br />";
//is there one record in the set?
if($sth->rowCount()!=1) {
echo "Error. No records were returned or more than one record was returned.<br />";
$validform = false;
} else {
echo $sth->rowCount() . " records returned.<br />";
$result = $sth->fetch();
$ID = $result['ID'];
$Cat = $result['Cat'];
$Description = $result['Description'];
}
//$result is an array that holds the dataset
if ($validform==false) {
echo "Data was invalid. Please contact technical support.";
} else {
echo "User wants to update Category with Category ID=". $ID ."<br />";
}
?>
Update Category Form
<form action="Update.php" method="post">
Category ID: <?php echo $ID; ?><input type="hidden" name="ID" value="<?php echo $ID; ?>">
<span style="color: red;"><?php echo $IDerrormessage; ?></span><br />
Category Name: <input type="text" name="title" value="<?php echo $Cat; ?>">
<span style="color: red;"><?php echo $Caterrormessage; ?></span><br />
Description: <textarea name="Description" style="width: 300px; height: 80px;">
<?php echo $Description; ?></textarea><br />
<span style="color: red;"><?php echo $Descriptionerrormessage; ?></span>
<input type="submit">
</form>
</body>
</html>
You're missing a space before FROM in this part of the code:
$SQL = "SELECT ID, Cat, Description";
$SQL .= "FROM Category WHERE ID=:ID;";
The code is interpreting the query as:
SELECT ID, Cat, DescriptionFROM Category WHERE ID=:ID;
Which is saying to select a column named DescriptionFROM and alias it as Category. Since there is no FROM clause, it is thrown off by the WHERE statement, which is why you're getting that error.
Adding a after Description and before FROM will render the query correctly:
$SQL = "SELECT ID, Cat, Description ";
$SQL .= "FROM Category WHERE ID=:ID;";
$SQL = "SELECT ID, Cat, Description";
$SQL .= "FROM Category WHERE ID=:ID;";
There is a space missing here! So the FROM is not detected and the WHERE seems out of place.
This is why I would strongly suggest not to do this kind of linebreaking!
You will encounter this type of error freqently when you break the line within a string. I suggest you use an editor that has the feature to break the line visually at a specific position.
I am getting 'Trying to get property of non-object error' for the 3 lines in the following code. What can be done to resolve this issue? My full code is:
$con=mysqli_connect("localhost","root","","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$data = json_decode(file_get_contents("php://input"));
$name = mysqli_real_escape_string($con, $data->name); //ERROR FOR THIS LINE
$address = mysqli_real_escape_string($con, $data->address); //ERROR FOR THIS LINE
$sql = "INSERT INTO friend_data(name,address) values ('$name','$address')"; //ERROR FOR THIS LINE
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Record Added";
mysqli_close($con);
Also I am getting 'Undefined variable: id' error for the following code:
$con=mysqli_connect("localhost","root","","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id']; //ERROR FOR THIS LINE
$sql = "delete from friend_data where id= '$id'";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Record Removed";
mysqli_close($con);
Can you show me your JSON data. And for second option try this
$id = $_GET['id'];
$con=mysqli_connect("localhost","root","","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "delete from friend_data where id= '$id'";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Record Removed";
mysqli_close($con);
You need to check that the variables are there before you do anything with them. For the second question you can't guarantee that id was passed in on the URL so do:
if (isset($_GET['id])) {
//do something
} else {
//show an error
}
for the first question again you cant guarantee that what came from "php://input" was a JSON string or that json_decode worked. Break the code into different stages and test that each worked before continuing rather than concatenating it all into a single line.
if (($content = file_get_contents("php://input")) !== FALSE) {
$data = json_decode($content);
if (($data != null) && (is_object($data))) {
//do your stuff
} else {
//error
}
} else {
`//error
}
I am trying to execute the function below but does not display anything.
function displayNr($x){
$sql="SELECT D4741 FROM table_x WHERE D4711='".$x."';
if (!$result = odbc_exec($pconn, $sql)) {
echo "Query error! ODBC: ", odbc_error();
} else {
while ($row = odbc_fetch_array($result)) {
echo $row["D4741"] . "\n";
}
}
}
displayNr('name');
However, if I remove the function it works correctly:
x='name';
$sql="SELECT D4741 FROM table_x WHERE D4711='".$x."';
if (!$result = odbc_exec($pconn, $sql)) {
echo "Query error! ODBC: ", odbc_error();
} else {
while ($row = odbc_fetch_array($result)) {
echo $row["D4741"] . "\n";
}
}
What could be the problem?
$pconn is not set in the function.
in the function, $pconn is a new local variable (with a scope of the function) and is not the same $pconn defined outside the function. pass it in as a parameter:
function displayNr($x,$pconn){
$sql="SELECT D4741 FROM table_x WHERE D4711='".$x."';
if (!$result = odbc_exec($pconn, $sql)) {
echo "Query error! ODBC: ", odbc_error();
} else {
while ($row = odbc_fetch_array($result)) {
echo $row["D4741"] . "\n";
}
}
}
displayNr('name');
watch out for SQL injection!!! your code is a perfect example of what not to do!!:
$sql="SELECT D4741 FROM table_x WHERE D4711='".$x."';
see this: SQL Injection or just google it
function displayNr($x, $pconn)
{
$sql = "SELECT D4741 FROM table_x WHERE D4711='" . $x . "'"; //here " is remaining
if (!$result = odbc_exec($pconn, $sql)) {
echo "Query error! ODBC: ", odbc_error();
} else {
while ($row = odbc_fetch_array($result)) {
echo $row["D4741"] . "\n";
}
}
}
displayNr('name');