user3753385
user3753385

Reputation: 37

How to write php code to update web service

I have a web service up and running, but I can only read the data from my database.

Could anyone help/guide into how I code the php file into being able to write to my database?

<?php

// Create connection
$con=mysqli_connect("server_address","database_name","user_name","table_name");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table ’table_name’
$sql = "SELECT * FROM table_name/";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();

// Loop through each row in the result set
while($row = $result->fetch_object())
{
    // Add each row into our results array
    $tempArray = $row;
    array_push($resultArray, $tempArray);
}

// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($result);
mysqli_close($con);
?>

Upvotes: 1

Views: 1622

Answers (3)

Cheruvian
Cheruvian

Reputation: 5877

You should get more familiar with MySql queries.

To update a table you would use something similar to the following query.

$sql = "
Update table_name 
Set    column1 = " . $value1 . ", 
       column2 = value2 
Where  column3 = matchingValue";

or

$sql = "
Inert Into table_name (column1, column2, column3) Values (value1, value2, value3)

Extra lines included for readability. You can put values directly into the sql via concatenation if you are not allowing user input.

You're going to want to use prepared statements for security reasons if you are letting users $_POST or $_GET

https://www.php.net//manual/en/mysqli.prepare.php

Though it is probably better to start using PDO

http://www.php.net//manual/en/book.pdo.php

Upvotes: 2

jsickles
jsickles

Reputation: 431

This isn't a PHP issue (yes, you're using PHP to execute the queries, but data insertion/retrieval is a SQL thing)

As @MarcB said, look up the INSERT syntax.

Upvotes: 0

Nicco
Nicco

Reputation: 286

$sql = "INSERT INTO table_name (column1) VALUES($value)"; will do the trick and you can extend with so many columns as you like.

Upvotes: 1

Related Questions