MySql Select Command returning null - php

I have a simple php code which enters value into MySql database and then retrieves it and displays it. However when retrieving it always return null and Empty Set is echoed everytime. Can someone please help.
I am using WAMP Server.
Database name is trial and name of table is People. It has 2 attributes: name and email id
Following is my code:
$con=mysqli_connect("localhost","root","");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_query($con,"INSERT INTO People VALUES ('xyz', 'abc#zzz.com')");
echo "Insertion Success";
$result = mysqli_query($con,"SELECT * FROM People");
if($result == null)
echo "Empty Set";
else
while($row = mysqli_fetch_array($result))
{
echo $row['name'] . " " . $row['emailid'];
echo "<br>";
}
mysqli_close($con);
?>

You should select a database after using mysqli_connect but before any queries are done:
$con=mysqli_connect("localhost","root","");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_select_db($con, "databasename");
//query processing here..

You should check if record is inserted change your code to
if( mysqli_query($con,"INSERT INTO People VALUES ('xyz', 'abc#zzz.com')") === FALSE){
echo mysqli_error();
}

first always check if you query executed write by executing it inside if():
if(!mysqli_query("your query"))
{
mysqli_error();
}
second i think your query is not executing because you cant name you table with a capital letter so it should be "people" not "People"

Related

Inserting array values and other from values of a form into two different mysql tables

I'am trying to insert data from a form into two different tables. Here's what I'am doing:-
<?php
$mysqli= new mysqli("localhost","root","","store_records");
if($mysqli->connect_error)
die("Database connection failed ".$mysqli->connect_error);
$query = "insert into bill_details(date,invoice_no,balance) values('".$_POST['p_date']."','".$_POST['invoice_no']."','".$_POST['balance']."')";
if($mysqli->query($query))
{
$cquery="";
for ( $i=0;$i<$_POST['row_numbers'];$i++)
{
$cquery .= "insert into bill_records(item_name,qty,pack,batch,expiry,mrp,rate,vat,discount,invoice_no) values('".$_POST['item_name'][$i]."','".$_POST['qty'][$i]."','".$_POST['pack'][$i]."','".$_POST['batch'][$i]."','".$_POST['expiry'][$i]."','".$_POST['mrp'][$i]."','".$_POST['rate'][$i]."','".$_POST['vat'][$i]."','".$_POST['discount'][$i]."','".$_POST['invoice_no']."');";
}
if($mysqli->multi_query($cquery))
echo "Records Saved";
else
echo "Failed to save product records";
}
else
{
echo "Failed To save Records";
}
?>
Now, data from the first query is getting stored into bill_details table. but the array values are not getting stored. I cant figure out what am I doing wrong with my code. I wanna know how can i solve this problem and use the invoice_no as reference key for both the tables.
Here are the structure of both the database tables..
bill_details table
bill_records table
Try this. Hope it works. :)
<?php
$mysqli= new mysqli("localhost","root","","store_records");
if($mysqli->connect_error)
die("Database connection failed ".$mysqli->connect_error);
$query = "insert into bill_details(date,invoice_no,balance) values('".$_POST['p_date']."','".$_POST['invoice_no']."','".$_POST['balance']."')";
if($mysqli->query($query))
{
$cquery="";
for ( $i=0;$i<$_POST['row_numbers'];$i++)
{
$cquery .= "insert into bill_records(item_name,qty,pack,batch,expiry,mrp,rate,vat,discount,invoice no) values('".$_POST['item_name'][$i]."','".$_POST['qty'][$i]."','".$_POST['pack'][$i]."','".$_POST['batch'][$i]."','".$_POST['expiry'][$i]."','".$_POST['mrp'][$i]."','".$_POST['rate'][$i]."','".$_POST['vat'][$i]."','".$_POST['discount'][$i]."','".$_POST['invoice_no']."');";
if(!($mysqli->query($cquery)))
die("failed to save");
}
}
else{
echo "Failed To save Records";
}
?>

Why are extra empty rows generated in mysql table when using php insert variables

I have tried to insert variable to mysql table from submitted html form. However, I observed that 3 rows is generated while I have just inserted 1 row of data variable. The problem disappeared when the data is not variable. This problem annoyed me very much. Hope problems can be solved. Thank you very much.
Below is the coding of creating the table:
<!DOCTYPE html>
<html>
<head>
<title>Server Database</title>
</head>
<body>
<span style='font-size:24;font-weight:bold;'>Server Database</span>
<br /><br />
<?php
$host="localhost";
$port=3306;
$socket="";
$user="root";
$password="";
$dbname="";
$conn = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
echo "it work"."<br>";
$SCusName=$_POST['CusName'];
$SCusChiName=$_POST['CusChiName'];
$SDate=$_POST['Date'];
$sql = "CREATE DATABASE db";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully"."<br>";
} else {
echo "Error creating database: " . $conn->error;
}
mysqli_select_db($conn,"db")
or die ('cannot select');
$sql = "CREATE TABLE Requests (
RequestNumber INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
CustomerName VARCHAR(50),
ChineseName VARCHAR(50),
DateOfRequest VARCHAR(30)
)";
if ($conn->query($sql) === TRUE) {
echo "Table Requests created successfully"."<br>";
} else {
echo "Error creating table: " . $conn->error;
}
$sql = "INSERT INTO Requests (CustomerName, ChineseName, DateOfRequest)
VALUES ('".$SCusName."', '".$SCusChiName."', '".$SDate."');";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "SELECT BbKeyID, CustomerName, ChineseName FROM Requests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "BbKeyID: " . $row["BbKeyID"]. " CustomerName: " . $row["CustomerName"]. " ChineseName: " . $row["ChineseName"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
The result in mysql table become contains three row as follow with a message 3 row(s) returned:
The first row contains correct data while the other two rows are empty in value only with the auto-incremented RequestNumber. Is the RequestNumber make the problems?
1 Result 1 Result 2 Result 3
2
3
The empty values are not NULL.
If the insert data is changed to:
$sql = "INSERT INTO Requests (CustomerName, ChineseName, DateOfRequest)
VALUES ('AAA', 'BBB', 'CCC')";
The result become correct and only one row given out as follow.
1 Result 1 Result 2 Result 3
Please help me to solve the problem. Thank you very much..
You run your INSERT query EVERY TIME the page is loaded, even if no form was submitted. So if the page is fetched via GET, you'll have undefined $_POST data, and insert empty strings.
You should have at least
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do db insert stuff here ...
}
to "hide" the code from non-post requests.
And you are vulnerable to sql injection attacks. Enjoy getting your server pwn3d.

Loop until the value is null

i need to loop the process of deleting if there is an id in the database that the user input. can someone help me about this?
//my php code
$ppnum=$_POST['pnum'];
while ($ppnum !== null)) {
$con=mysqli_connect("","","","");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM tbldd WHERE pnum ='$ppnum'");
mysqli_close($con);}
maybe you want this? This assume $_POST['pnum'] is comma separated list of ids.
$ppnum=$_POST['pnum'];
$con=mysqli_connect("","","","");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM tbldd WHERE pnum in ($ppnum)");
mysqli_close($con);
but you MUST check $_POST['pnum'] against sql injection attack.

PHP Mysqli SELECT, INSERT and UPDATE from different databases

I am trying to select values from one DB. And insert and update the result into another. This is cronjob that needs to run everyday to replicate some data from one DB into another. I know I am missing steps / correct syntax, but I hope someone can help me out.
<?php
$con_1=mysqli_connect("host","user","pw","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$con_2=mysqli_connect("host","user","pw","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con_1,"SELECT id, name FROM table GROUP BY 1,2");
$mysqli->query($con_2, "INSERT INTO `table2`(`id`, `name`) VALUES ('".$result[1]."', ".$result[2].")
ON DUPLICATE KEY UPDATE name = ".$result[2]."");
}
mysqli_close($con_1);
mysqli_close($con_2);
?>
mysqli_query returns a query object, using $result[1] doesn't make sense, you need to fetch the rows in a loop:
while($row = $result->fetch_assoc()) {
// insert result in second database
}
For other access methods check the documentation.

Delete only certain things from database

I got this php script from w3schools and I was wondering if its possible to only delete the last name and leave the first name which is peter?
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");
mysqli_close($con);
?>
source:
http://www.w3schools.com/php/php_mysql_delete.asp
Yes, just do
UPDATE Persons
set LastName = ''
WHERE
id = ?
or alternatively set LastName = NULL

Categories