最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to connect to SQL database with react? - Stack Overflow

programmeradmin2浏览0评论

I currently have a website, written in HTML and PHP, that can access my SQL database. I have now started learning React and want my super simple website to also connect to an SQL database.

Previously i've done this:

<php
    $conn = mysqli_connect($serverIP, $dbusername,$dbpassword,$dbname);
    if(mysqli_errno($conn)) {
     die("<p>MySQL error:</p>\n<p>" . mysqli_error($conn) . "</p>\n</body>\n</html>\n");
    }
?>

and then in the index.php file, done this:

<?php include_once "connection.php"; ?>

And continued with basic SQL to fetch data.

How do I do the same in React? More specifically, how do I write PHP in React to be able to connect to an SQL database? How does this code look like?

Also, as I am learning React on my own it would be great if there was a place where people could review code, and where I could receive tips on improvement. Is there such a website/munity?

I currently have a website, written in HTML and PHP, that can access my SQL database. I have now started learning React and want my super simple website to also connect to an SQL database.

Previously i've done this:

<php
    $conn = mysqli_connect($serverIP, $dbusername,$dbpassword,$dbname);
    if(mysqli_errno($conn)) {
     die("<p>MySQL error:</p>\n<p>" . mysqli_error($conn) . "</p>\n</body>\n</html>\n");
    }
?>

and then in the index.php file, done this:

<?php include_once "connection.php"; ?>

And continued with basic SQL to fetch data.

How do I do the same in React? More specifically, how do I write PHP in React to be able to connect to an SQL database? How does this code look like?

Also, as I am learning React on my own it would be great if there was a place where people could review code, and where I could receive tips on improvement. Is there such a website/munity?

Share Improve this question edited Oct 25, 2018 at 20:38 glennsl 29.1k12 gold badges59 silver badges79 bronze badges asked Oct 25, 2018 at 20:25 Fredrik BurmesterFredrik Burmester 2392 gold badges4 silver badges12 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 10

I think you may not understand how to layers quite fit together yet (don't worry - it takes some time to wrap your head around). In your case, your server-side (PHP) code will make all of your database calls and retrieve / modify any data you need (you don't want to have your database credentials viewable on the client-side, after all!).

In order to display or change data from your React JS front-end, you'll need a way to municate these intentions to the backend; this can be done by creating REST endpoints in your PHP codebase, which you will then need to call from your React JS code (you can use Axios, fetch or many other HTTP libraries for this).

Here's a super simple example that I grabbed from /u/roboctocat on reddit: https://www.reddit./r/reactjs/ments/8lb6u3/can_anyone_provide_me_a_basic_example_tutorial/

Your client code:

// index.jsx
class MyComponent extends React.Component {
    onClick() { 
        fetch("http://your-php-server/ping-pong.php")
            .then(res => res.json()) 
            .then((result) => { console.log(result); }) 
    }

    render() { 
        return ( 
            <button onClick={this.onClick} /> 
        ); 
    } 
}

And your server code:

// ping-pong.php
<?php
    header('Content-Type: application/json'); 
    echo json_encode(array('ping' => 'pong')); 
?>

Try this

const getData()=>{
  //function to fetch data
  const handleData=()=>{
    axios.get('php file path')
      .then(response=>response.json())
      .then((data)=>console.log(data.json));{

    }
  }

  return(
  <>
      <button onClick={handleData}></button>
  </>
  );
} //end main

export default getData()

First of all i suggest you to write your php code as below:

 $conn = mysqli_connect($serverIP, $dbusername,$dbpassword,$dbname);
    if(mysqli_errno($conn)) {
     
     $connError = array(
         "status" => boolval(0),
         "error" => mysqli_errno($conn)
     );

     $error = json_encode($connError);

     die($error);
    }

Now you get much better response to handle in React from your backend.

Then in next step you can call fetch api to send request to your backend and check the database connection:


useEffect(() => {
  fetch("https://your-server/connection.php")
    .then((response) => response.json())
    .then((res) => console.log(res));
}, []);

Now with useEffect() hook you can check the database connection once on each page load.

Also you can check if typeof for res is array then do something like showing error message to user.

I hope it helped.

If you are open to mercial alternatives, lolaDB is a great option to connect to most major databases without any backend/API code.

const data = await loladb.query.execute({
  queryId = "get-all-recent-orders"
})

// data = [{ "orderId" : 123, .... }]
发布评论

评论列表(0)

  1. 暂无评论