i trying create search engine mysql table jquery, ajax , php. have database on external server in order data from. here pic of mysql database table. 
have these 2 scripts search engine:
index.html
<!doctype html> <html> <head> <meta charset="utf-8"> <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> </head> <body> <input id="searchdb"/> <div id="resultdb"></div> <script type="text/javascript"> $(document).ready(function() { $('#searchdb').change(function() { $.ajax({ type: 'get', url: 'getdb.php', data: 'ip=' + $('#searchdb').val(), success: function(msg) { $('#resultdb').html(msg); } }); }); }); </script> </body> </html> getdb.php
<?php if ($_get['insert']) : $insert = preg_replace('#[^0-9]#', '', $_get['insert']); $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "mydb"; // create connection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $sql = "select id, name test id='.$insert.'"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row $row = $result->fetch_assoc() echo $row["name"]; } endif; ?> what want type id, hit enter , name or "0 results". there seems wrong code wrote. please me? in advance.
the period characters in sql text string being interpreted literal dot characters, not php concatenation.
e.g.
$sql = "select id, name test id='.$insert.'"; echo "sql=" . $sql; should return:
sql=select id, name test id='.123.' that easy enough fix. why include value part of sql text in first place.
using prepared statements , bind placeholders not hard.
use static string sql statement, use question mark bind place holder, , call mysqli_stmt_bind_param function. , check prepare , execute calls errors. (those return false if error occurs.) , call num_rows isn't necessary. fetch. if returns row, you've got row. if returns false, there wasn't row return.
something this:
$sql = "select id, name test id = ? "; if ($stmt = $conn->prepare($sql)) { $stmt->bind_param("i",$insert); if ($stmt->execute()) { if ($row = $stmt->fetch_assoc()) { echo $row['name']; } else { echo "0 results"; } } else { // handle error die $conn->error; } } else { // handle error die $conn->error; } you handle error conditions differently, depending on requirements.
Comments
Post a Comment