I'm trying to make something which will only display the name of the row which has ID 1 but I can't seem to get it to work. I can make it display all the names but I only want it to display the name of user ID 1. This is my current code but it doesn't work.
<a style="font-size: 17px; color: #ff0000;"><?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result=mysqli_query($q);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row != FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo $name;
} else{echo "it's false :(";};
?></a>
It returns:
it's false :(
you may need the while() check on there.
Try something like:
Your database connection:
$servername = "YOUR_HOST";
$username = "YOUR_USER";
$password = "YOUR_PASSWORD";
$dbname = "YOUR_DATABASE";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then your main file with displaying the row you want:
// create query
$q = "SELECT * FROM Team WHERE id = 1";
// get the records from the database
if ($result = $mysqli->query($q))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// fetch the results
while ($row = $result->fetch_object())
{
$name = $row->name;
echo $name;
}
}
else
{
echo "No results to display!<br><hr><br>";
}
}
else
{ // show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
mysqli_query requires first parameter should be connection string and second is the query
mysqli_query($link, "your query");
Ref: http://php.net/manual/en/mysqli.query.php
You need to add the Connection-Parameter!
$result=mysqli_query($db, $q);
instead of
$result=mysqli_query($q);
Related
function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
if($row["red"] == ""){
echo "";
}else{
while($row = mysqli_fetch_assoc($result)){
echo "<input type='image' src=" . $row["red"]. ">";
}
mysqli_close($con);}}
In PHP I have row "red" filled with link to MShirt/redshirt.png. This code should create an input with this image but if is empty shouldn't create input. Now, this doesn't work even with a filled row.
You have a number of problems with your code, but the main one is that mysqli_num_rows() does not return data. It tells you how many records were fetched from the database into PHP.
You don't need mysqli_num_rows() in your code.
You don't need mysqli_close($con);, especially not inside of the loop.
You don't need the while loop. This is an old way of iterating. Use foreach instead.
You don't need if/else and echo "". You only need the positive condition.
Here is your code fixed:
function getConnection() {
// enabler error reporting, create an instance and set the correct charset
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli('localhost', 'root', '', 'shop');
$con->set_charset('utf8mb4');
return $con;
}
function getRed() {
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = $con->query($sql);
foreach ($result as $row) {
if ($row["red"] != "") {
echo "<input type='image' src=" . $row["red"] . ">";
}
}
}
The function mysqli_num_rows() returns only the count of results returned by your query, the mysqli_fetch_assoc() is the one going through the results. I would suggest taking the mysqli_close($con); outside the if statement as shown.
<?php
function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0) {
while($row = mysqli_fetch_assoc($result)){
if(isset($row["red"]) && $row["red"] != "") {
echo "<input type='image' src=" . $row["red"]. ">";
}
}
}
mysqli_close($con);
}
I don't know what this input should work for, but I assume you want to simply embed an image. Use it like this:
$result = mysqli_query($con, $sql);
while ($row= mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
mysqli_num_rows is used to count how many rows are in the result, it returns the number of rows which you can not read like an array...
$result = mysqli_query($con, $sql);
$row_count = mysqli_num_rows($result);
echo $row_count.' rows in result.';
while ($row = mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
Please make sure to understand basic HTML before getting into PHP and MySQL, also do not do database queries without getting to know proper security standards.
I wrote simple code to fetch data from MySQL using PHP.
This is the code:
<?php
$mangkal = $_POST['mangkal'];
$lat = $_POST['lat'];
$long = $_POST['long'];
$mysqli = new mysqli("localhost", "root", "", "mad");
$query = "SELECT * FROM kendaraan WHERE mangkal LIKE '%$mangkal%' ORDER BY id DESC";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_BOTH);
{
echo "<p>";
echo "$row[id_kendaraan]";
echo "<p>";
echo "$row[mangkal]";
}
?>
The script is working, if the data is returned by the db call, I can see the results displayed. But, if the query result has no data, the script just displays blank. I want to show a message that says - 'Data not found'. How can I do that?
I have more than one record for a query but the script displays just one data. Please help me to show all records.
Use a while loop like following:
if($result->num_rows > 0)
{
while($row = $result->fetch_array(MYSQLI_BOTH))
{
echo "<p>".$row[id_kendaraan]."</p><br><p>".$row[mangkal]."</p>";
}
} else {
echo "No Record Found.";
}
You need to run a loop to iterate through each result. Something similar to this -
<?php
$mangkal = $_POST['mangkal'];
$lat = $_POST['lat'];
$long = $_POST['long'];
$mysqli = new mysqli("localhost", "root", "", "mad");
$query = "SELECT * FROM kendaraan WHERE mangkal LIKE '%$mangkal%' ORDER BY id DESC";
$result = $mysqli->query($query);
while($row = $result->fetch_array(MYSQLI_BOTH)) {
echo "<p>";
echo "$row[id_kendaraan]";
echo "</p><p>";
echo "$row[mangkal]";
echo "</p>";
}
?>
In the code above, a while loop is used to iterate through results one by one. Each time $row will be updated with new data and will be printed.
Here's what i tried.
I've Tried fetch the data from DB.It shows data from the start of the iteration to the End of iteration.I need only last iteration value.I'm a complete noob. A help would be appreciated
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
$conn = new mysqli($servername, $username, $password, $dbname);
$myarray=array();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myarray[]= $row;
// echo "<pre>";
// print_r($myarray);
echo "<pre>";echo json_encode($myarray);
// echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Description :" . $row["description"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Change your SQL query to
SELECT id, name, description FROM products order by id desc limit 1
That will work for you.
Finally, I got your point that what you want-
You need to get all record in one variable.Which you can encode at last
For that do like below:-
1.Initialize array outside of the loop
2.Assign each record to the array inside the loop
3.Encode array outside the loop
Do like below:-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
$conn = new mysqli($servername, $username, $password, $dbname);
$myarray=array();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM products";
$result = $conn->query($sql);
$myarray = []; //Initialize array outside of the loop
if ($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myarray[] = $row; //Assign each record to the array inside the loop
}
} else {
echo "0 results";
}
$conn->close();
echo json_encode($myarray);//Encode array outside the loop
?>
While it looks like a duplicate to me, I would suggest the following, assuming that you are not intending to sort the dataset from the DBMS.
Use mysqli_data_seek ( mysqli_result $result , int $offset ) to move cursor that traverses the dataset. So for your case it would be
$nor = mysqli_num_rows($result); //Number of rows
mysqli_data_seek($resutl, ($nor - 1)); //Indices are based on 0
Basically $nor contains the total number of records. So the index of the last ever record would be $nor-1.
Of course if you are sorting the dataset in your query using ORDER BY, then the best way to do this is appending ORDER BY id DESC LIMIT 1.
through a cURL connection, I can pick up data, from Json files, placed on a remote server. In particular, the codes of some products, which thanks to a foreach
foreach($data['results'] as $key=>$val){
$codici_hotel = $val['hotel_code'];
echo $codici_hotel.",";
}
I can see on video:
1074d0,19f726,1072ba,107104,183444,112438,15d8ab,1b326e,19d885,189b95,1071bf,107155,193e61,10aab2,138752,18dd7d,19d7f9,117b0d,1071b8,1398c4,107039,110851,107124,110669
Now I need to use that string to run a select on a local database, such as:
$sql = "SELECT * FROM hotels WHERE code = ('$codici_hotel')";
What is the correct sql string?
Thanks for your help
CODE UPDATE USED
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT name FROM hotels WHERE code IN ('$codici_hotel')";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$nome_hotel = $row2["name"] ;
}
} else {
echo "0 results";
}
$conn2->close();
echo $nome_hotel;
You have to convert your all codes in string enclosed with '. Then use IN clause of mysql. change your code as below
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$sql = "SELECT * FROM hotels WHERE code IN ($codici_hotel)";
I've created a table and stored values in it. The table has a column 'ID' which is unique.
Now I’ve created a form where there is a button marked Retrieve. When I enter the ID and click the Retrieve button, I want to view the data corresponding to this ID.
How do I do this using PHP and MYSQL?
I’ve got some code below, but it isn‘t working. No error message is being showed. But there is no problem with the db connection. Rest of the functions working except for 'RETRIEVE'.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".'$id'."";
$dis = $db->query($retrieve);
$row = $dis->fetch_assoc();
echo 'Details are: '.$row['id'];
}
}
$conn->close();
?>
Change sql select clause into this:
"SELECT * FROM ins WHERE Id = " .$id. " LIMIT 1";
$retrieve = "SELECT * FROM ins WHERE Id = ".$id." LIMIT 1";
The limit will work for you
In the SQL statement ($retrieve), the single quotes are killing it for you. Try either of the following:
Remove the single quotes around $id and keep the rest of the statement the same
Change '$id' to "'{$id}'" (if you're keen on getting the single quotes around the $id value - just in case $id is a text value and not a number)
Try this
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
$dis = $db->query($retrieve);
$row = $dis->fetch_row();