Mysql delete a row php - php

I have a MySQL table and i would like to delete a row in my table and after deleting the row the result must show all data left in my table .
<?php
include 'Connection.php';
// Create connection
$con= mysqli_connect($host,$user,$pass,$db);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$sql = "SELECT * FROM productos";
$result = $con->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc())
{
$tem = $row;
$json = json_encode(array("productos"=>$tem));
}
} else {
echo "No Results Found.";
}
echo $json;
$con->close();
?>
This is my select code... now i don't know how create the delete function..
Any help please.

You are overwritting, make array of rows and then echo json_encode at last
$items = array();
if ($result->num_rows >0) {
while($row = $result->fetch_assoc())
{
$items[] = $row;
}
} else {
echo "No Results Found.";
}
echo json_encode(array("productos"=>$items));
$con->close();

Related

php echo json_encode from DB entries -> getting strange format. how to get a proper JSON

At the moment i get the following JSON:
["1Sales & Consulting","2Pyments","3Investing","4Financing","5Cross Functional"]
but i would like to have a proper JSON like:
[{"id":1, "name": "Sales & Consulting"}{"id": 2, "name": "Pyments"}{"id": 3, "Investing"}{"id": 4, "name": "Financing"}{"id": 5, "name": "Cross"}]
The code i used to generate the first output is:
<?php
define('servername','localhost');
define('username','root');
define('password','');
define('dbname','integration');
// 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 FROM capability_level1";
$result = $conn->query($sql);
$test = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$test[] = $row["id"] . $row["name"];
}
echo json_encode($test);
} else {
echo json_encode("0 results");
}
$conn->close();
?>
what do i have to change? this echo is needed to pass to ajax in a second step
Change the lines
while($row = $result->fetch_assoc()) {
$test[] = $row["id"] . $row["name"];
}
to
while($row = $result->fetch_assoc()) {
$test[] = array(
'id' => $row["id"],
'name' => $row["name"]
);
}
Hope this helps.
Try this instead:
while($row = $result->fetch_object()) {
array_push($test, $row);
}
echo json_encode($test);
Use the following code changes:-
<?php
$result = $conn->query($sql);
$test = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($test, $row);
}
echo json_encode($test);
} else {
echo json_encode("0 results");
}
$conn->close();
?>

Conditional Logic on MySQL Query with PHP

I am doinga MySQL query to retreive data using PHP. I need to have a logic that if the data set returned is empty it shows a warning message else it displays the results:
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
mysqli_close($conn);
You need num_rows on the object
$result = mysqli_query($conn,$sql);
if ($result->num_rows == 0) {
echo 'result empty';
} else {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
}
http://php.net/manual/en/mysqli-result.num-rows.php
Change mysql_escape_string to mysqli_escape_string here
$where = "";
if(isset($_POST['searchQuery']) && trim($_POST['searchQuery'])){
$searchQuery = mysqli_escape_string($conn,$_POST['searchQuery']);
$where =" WHERE column1 = '".$searchQuery."'";
}
$sql="SELECT * FROM db.tblname ".$where;
It's as simple as this:
if ($result) {
//Your code
} else {
echo "Error: ".mysqli_error($conn);
}
First check with mysqli_num_rows(). Here is how to
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
}
else {
echo "No records found";
}
mysqli_close($conn);
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
} else {
echo "No results found";
}
mysqli_close($conn);

PHP - Multiple Select queries based on If else conditions

I need help with Multiple Select queries based on If else conditions. I've multiple tables and I want to work queries like this.
Search in table1, if found then return the result.
If not found then search in table2.
If word not found in both table1 and table2 then check in table3 and after that check in table4
I'm using below codes.
<?php
// 1. Create a database connection
$mysqli = new mysqli("localhost", "root", "", "us");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = $mysqli->real_escape_string($term);
if($term=="") {
echo "Enter Something to search";
exit();
}
if(
$result = $mysqli->query("Select * from table1 where word like '{$term}%'
UNION
Select * from table2 where word like '{$term}%'")){
$num_rows = $result->num_rows;
if(mysqli_num_rows($result) >= 0) {
while($row = $result->fetch_assoc())
{
echo "Stem : {$row['word']} <br>";
}
}
else {
$result = $mysqli->query("Select * from table3 where words like '{$term}%'");
$num_rows = $result->num_rows;
if(mysqli_num_rows($result) >= 0) {
while($row = $result->fetch_assoc())
{
echo "words: {$row['words']} <br>";
}
}
}
}
else{
echo "No matches found!";
}
?>
try
str_replace($row['prefix'],'',$term );
<?php
mb_internal_encoding( 'UTF-8');
$mysqli = new mysqli("localhost", "root", "", "us");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->query("SET WORDS 'utf8'");
$mysqli->query('SET CHARACTER SET utf8');
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = $mysqli->real_escape_string($term);
if($term=="") {
echo "Enter Something to search";
exit();
}
termcheck($term, $mysqli);
function termcheck($term, $mysqli){
$qry="Select * from table1 where word ='$term' UNION Select * from table2 where word = '$term'";
if($result = $mysqli->query($qry)){
//echo "inside sql table1";
$num_rows = $result->num_rows;
if($num_rows > 0) {
//echo "inside table1";
while($row = $result->fetch_assoc())
{
echo "Stem : ".$row['term']."<br>";
}
exit();
}
}else {
$qry1="Select * from table3";
$result = $mysqli->query($qry1);
$num_rows = $result->num_rows;
if($num_rows > 0) {
while($row = $result->fetch_assoc()){
echo "inside while";
if($table4=mb_strrichr($term,$row['prefix'])){
echo "inside if";
$sterm=str_replace($row['prefix'],'',$term);
$postfix=$row['prefix'];
echo "inside : ".$sterm;
}
}
}else{echo "Error : Table3 doesn't exist";}
}
if(!empty($sterm)){
$qry3="Select * from table4";
$result3 = $mysqli->query($qry3);
$num_rows = $result3->num_rows;
if($num_rows > 0) {
while($row = $result3->fetch_assoc()){
if(mb_strrichr($sterm,$row['postfix'])){
$ssterm=str_replace($row['postfix'],'',$sterm);
$prefix=$row['postfix'];
echo "prefix : ".$prefix;
echo "<br>";
echo "postfix : ".$postfix;
echo "<br>";
echo "sterm : ".$ssterm;
}
}exit();
}else{echo "Error : Table3 doesn't exist";}
}else{
$qry3="Select * from table4";
$result3 = $mysqli->query($qry3);
$num_rows = $result3->num_rows;
if($num_rows > 0) {
while($row = $result3->fetch_assoc()){
if(mb_strrichr($term,$row['postfix'])){
$prefix=$row['postfix'];
$sterm=str_replace( $row['postfix'],'',$term);
echo "prefix : ".$prefix;
echo "<br>";
echo "sterm : ".$sterm;
}
}exit();
} else{echo "Error : Table3 doesn't exist";}
}
}
?>

If 0 items in DB table, return error

I am looking for a way to display an error message if there is nothing listed in the table.
I have a photos table.
If this tables is empty, id like to echo something.
else, show the pictures.
inside of that table I have
id, name, url
id = id
name = name of image
url = url of image.
If there are no rows, we have an error.
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
mysql_fetch_array($query1);
if(empty($query1)) {
echo "nothing";
} else {
echo "good";
}
Try this,
$query = "SELECT * FROM photos";
$result= mysql_query($query);
$length= mysql_num_rows($result);
if($length>0)
{
while($rows = mysql_fetch_array($result))
{
echo $rows['name'];
echo "<img src='$rows[url]' />";
}
}
else
{
echo "Nothing to display";
}
Hope this will work
What about something like...
$sql = "SELECT COUNT(*) AS amountPhotos FROM photos";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row["amountPhotos"] == 0) {
echo "There are no photos in the photo table.";
}
or
$sql = "SELECT * FROM photos LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "There are no photos in the photo table.";
}
Try this
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
$result = mysql_fetch_array($query1);
if(empty($result)) {
echo "nothing";
} else {
echo "good";
}
This pretty much sums up the answer for this question: http://www.w3schools.com/php/php_mysql_select.asp
They even provided a sample code:
<?php
$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, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //<--- here they check if number of rows returned is greater than 0 (so there is data to display)
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results"; //<----- nothing found
}
$conn->close();
?>
Just modify this and you'll be good to go.

trouble retrieving data from sql database with php

I'm pretty new to php, and I'm teaching myself. I've looked at a few different resources, and the php script I have now doesn't return any critical errors when executed, but its not returning the data from the table.
<?php
$connect = mysqli_connect("localhost","*","*","*");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$comments = "SELECT * FROM commentstable";
$rs = mysqli_query($connect,$comments);
$fetch = mysqli_fetch_array($rs);
while($fetch = mysqli_fetch_array($rs)) {
echo $fetch['comments'];
}
echo $fetch;
mysqli_close($connect);
echo "hello";
?>
you have double entry:
$fetch = mysqli_fetch_array($rs); //<--- remove this as you are calling it again in the while loop
while($fetch = mysqli_fetch_array($rs)) {
echo $fetch['comments'];
}
Check this
$connect = mysqli_connect("localhost","turlough","samus1","comments");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$comments = "SELECT * FROM commentstable";
$rs = mysqli_query($connect,$comments);
if($rs)
{
while($fetch = mysqli_fetch_array($rs)) {
echo $fetch['comments'];
}
}
else
{
// no results from query
}
mysqli_close($connect);
}

Categories