How to count number of rows from a table using PHP - php

I am trying to get the count of number of rows from Vulnerability table based on the vulnerability and threat entered. But always i get a value None in place of vulnerability count.
$link = mysqli_connect("localhost", "root", "sharmi#08", "MySQL56");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$Vulnerability = mysqli_real_escape_string($link, $_POST['Vulnerability']);
$Threat = mysqli_real_escape_string($link, $_POST['Threat']);
/*$P_Vulnerability = mysqli_real_escape_string($link, $_POST['P_Vulnerability']);*/
/*$P_Threat = mysqli_real_escape_string($link, $_POST['P_Threat']);*/
$Threat_count = mysqli_real_escape_string($link, $_POST['Threat_count']);
$table = mysqli_real_escape_string($link, $_POST['Vul']);
// attempt insert query execution
$sql = "INSERT INTO vuln_threat(Vulnerability, Threat) VALUES ('$Vulnerability', '$Threat') ";
$Vulnerability_count = mysqli("Select count(*) from vuln_threat");
$sql = "UPDATE vuln_threat SET Vulnerability_Count='$Vulnerability_count',Threat_Count='1' WHERE Vulnerability='".$Vulnerability."' AND Threat='".$Threat."'";
//$select_result = mysqli_query($query);
if ( mysqli_query($link, $sql, $query)) {
echo "New Records added successfully." ;
} else {
echo "Please add records." ;
}
// close connection
mysqli_close($link);

mysqli_query accepts only predefined constants as the 3rd parameter when used in a procedural fashion.
http://php.net/manual/en/mysqli.query.php

Related

How do I display data using the url

How do I display the information data using the ID in the url
example is www.thatsite.com/?id=1092
and it will display the data of the 1092 ID
<?php
$connect = mysqli_connect("localhost", "xxxxxxx", "xxxx","xxxx");
$query = "SELECT `name`, `age`, `xxxxx` , `xxxxx`, `image` FROM `profiles` WHERE `id` = $id LIMIT 1";
$id=$_GET['id'];
$result = mysqli_query($connect, $query,$id);
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
echo $row['xxxx'];x
echo $row['age'];
echo $row['xxxxxxx'];
echo $row['image'];
}
?>
Your code is full of security holes. It is prone to sql injection, xss attack, csrf, html injection.
I have re-written it to circumvent all the issues.
1.) Sql Injection is now mitigated using prepare queries
2.) Html injection is mitigated using intval for integer variables and strip_tags for strings. you can read more about data validations and sanitization in php to see more options available
3.) xss attack has been mitigated via htmlentities().
you can also use htmlspecialchars(). Read more about all this things
see better secured codes below
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ur dbname";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
// ensure that the Id is integer using intval
$id = intval($_GET["id"]);
// if id is a string. you can strip all html elements using strip_tags
//$id = strip_tags($_GET["id"]);
//Avoid sql injection using prepared statement
// prepare and bind
$stmt = $connect->prepare("SELECT name, age , xxxxx, image FROM profiles WHERE id = ? LIMIT 1");
// id is integer or number use i parameter
$stmt->bind_param("i", $id);
// id is integer or number use s parameter
//$stmt->bind_param("s", $id);
$stmt->execute();
$stmt -> store_result();
$stmt -> bind_result($name, $age, $xxxxx, $image);
while ($stmt -> fetch()) {
// ensure that xss attack is not possible using htmlentities
echo "your Name: .htmlentities($name). <br>";
echo "your age: .htmlentities($age). <br>";
echo "your xxxxx: .htmlentities($). <br>";
echo "your image name: .htmlentities($image). <br>";
}
$stmt->close();
$connect->close();
?>
from https://www.w3schools.com/php/php_mysql_select.asp
leave out the 'get id', the id is in the SQL:
$id=$_GET['id'];
The similar example at
https://www.w3schools.com/php/php_mysql_select.asp
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);

MySQL query no results

I want echo my DB results from Session but i get no results or errors:
$_SESSION['username'];
$link = mysqli_connect("$myHost", "$myUser", "$myPass", "$myDB");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$username = mysqli_real_escape_string($link, $_SESSION['username']);
$sql = "SELECT * FROM users where username = $username";
$result = mysqli_query($link, $sql);
echo $result;
Anyone know why not? Session works.
Thanks
You should change your query, like this:
$sql = "SELECT user FROM yourtablename WHERE username = $username"
Where "user" is what you want to SELECT if you want to select all data, you can use "*", yourtablename is table name of table you want to select.
After your edits, your code should look like
$_SESSION['username'];
$link = mysqli_connect("$myHost", "$myUser", "$myPass", "$myDB");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$username = mysqli_real_escape_string($link, $_SESSION['username']);
$sql = "SELECT * FROM users where username = $username";
if ($result = $link->query($sql)) {
while ($row = $result->fetch_row()) {
var_dump($row);
}
$result->close();
}
More info here
Notice: mysqli_real_escape_string it's not very security. A better option to protect against SQL injections is using prepared statements, more info here

uploading images to mysql second table

I am working on a php form that submits data to one table and then images to a second table in my mysql database.
The bit i am stuck on is submitting to the second table for what ever reason it just doesnt seam to be working.
Can someone please point me in the right direction to where i am going wrong with this code?
Any help at all would be greatly appreciated
<?php
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
$link = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$id = mysqli_real_escape_string($link, $_POST['id']);
$title = mysqli_real_escape_string($link, $_POST['title']);
$price = mysqli_real_escape_string($link, $_POST['price']);
$sqm = mysqli_real_escape_string($link, $_POST['sqm']);
$sqm_land = mysqli_real_escape_string($link, $_POST['sqm_land']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$area = mysqli_real_escape_string($link, $_POST['area']);
$location = mysqli_real_escape_string($link, $_POST['location']);
$bedroom = mysqli_real_escape_string($link, $_POST['bedroom']);
$terrace = mysqli_real_escape_string($link, $_POST['terrace']);
$orientation = mysqli_real_escape_string($link, $_POST['orientation']);
$water = mysqli_real_escape_string($link, $_POST['water']);
$seaview = mysqli_real_escape_string($link, $_POST['seaview']);
$pool = mysqli_real_escape_string($link, $_POST['pool']);
$ownerinfo = mysqli_real_escape_string($link, $_POST['ownerinfo']);
$gaddress = mysqli_real_escape_string($link, $_POST['gaddress']);
$description = mysqli_real_escape_string($link, $_POST['description']);
$image = mysqli_real_escape_string($link, $_POST['image']);
$lastid = mysqli_real_escape_string($link, $_POST['lastid']);
$seq = mysqli_real_escape_string($link, $_POST['seq']);
// attempt insert query execution
$sql = "INSERT INTO property (title, price, sqm, sqm_land, type, area, location, bedroom, terrace, orientation, water, seaview, pool, ownerinfo, gaddress, description) VALUES
('$title', '$price', '$sqm', '$sqm_land', '$type', '$area', '$location', '$bedroom', '$terrace', '$orientation', '$water', '$seaview', '$pool', '$ownerinfo', '$gaddress', '$description' )";
function insertimages($image,$lastid,$seq){
$query="insert into images(imagepath,property_id,imageorder) values('".$image."','".$lastid."','".$seq."')";
$this->execQuery($query);
}
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Here you have declared the insertimages function but not calling. You can call like this:
if(mysqli_query($link, $sql)){
insertimages($image,$lastid,$seq);
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

not response for database

This is the code for database connection in php:
<?php
$connection = mysql_connect("localhost", "root", "root"); // Establishing Connection with Server
$db = mysql_select_db("fimos", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$gender = $_POST["gender"]; //declare gender
$race = $_POST["race"];
$ic = $_POST["icno"];
$name = $_POST["name"];
$old_ic = $_POST["oldic"];
$add1 = $_POST["add1"];
$add2 = $_POST["add2"];
$add3 = $_POST["add3"];
$postcode = $_POST["postco"];
$town = $_POST["tow"];
$state = $_POST["state"];
$home_con = $_POST["homep"];
$fax_contact = $_POST["fax"];
$hp_con1 = $_POST["mobi1"];
$hp_con2 = $_POST["mobi2"];
$email = $_POST["email"];
if($ic !=''||$email !=''){
//Insert Query of SQL
$query = mysql_query("INSERT INTO customer_info(cust_gender, cust_race, cust_ic,
cust_name, cust_old_ic, cust_add1, cust_add2, cust_add3, cust_postcode,
cust_town, cust_state, cust_home_con, cust_fax_contact, cust_hp_contact1,
cust_hp_contact2, cust_email)
VALUES ('$gender', '$race', '$ic' , '$name', '$old_ic', '$add1', '$add2',
'$add3', '$postcode', '$town', '$state', '$home_con', '$fax_contact',
'$hp_con1', '$hp_con2', '$email')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
Hi guys, I want to ask about the database connection, is it my code wrong somewhere?
Because I cant found any error in the code.
I click button register should come over this page to store the data.
when I come to this page display all blank.
I try to change the database name also no response.
I hope you guys can help me.
Thanks.
It should be:
$connection = mysql_connect("localhost", "root", ""); //empty the third parameter. If you have password then insert that in your third parameter
Paste this code inside your if condition so that it will return error from your sql query.
if (!$query) {
die('Invalid query: ' . mysql_error());
}
Try to use the PDO extension instead of mysql & mysqli function. The mysql_* functions are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi there are lots of benefits of using PDO over mysqli.
Add the above code
if($ic !=''||$email !=''){
$query = mysql_query("your query");
if (!$query) {
die('Invalid query: ' . mysql_error());
} else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
}

Selecting certain row in mysql

I am completely new to MYSQL and PHP, so i just need to do something very basic.
I need to select a password from accounts where username = $_POST['username']... i couldn't figure this one out, i keep getting resource id(2) instead of the desired password for the entered account. I need to pass that mysql through a mysql query function and save the returned value in the variable $realpassword. Thanks!
EDIT:
this code returned Resource id (2) instead of the real password
CODE:
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = $_POST['username'];
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
echo "$new";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
It will be a lot better if you use PDO together with prepared statements.
This is how you connect to a MySQL server:
$db = new PDO('mysql:host=example.com;port=3306;dbname=your_database', $mysql_user, $mysql_pass);
And this is how you select rows properly (using bindParam):
$stmt = $db->prepare('SELECT password FROM accounts WHERE username = ?;');
$stmt->bindParam(1, $enteredusername);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$password = $result['password'];
Also, binding parameters, instead of putting them immediately into query string, protects you from SQL injection (which in your case would be very likely as you do not filter input in any way).
I think your code looks something like this
$realpassword = mysql_query("SELECT password
from accounts where username = '$_POST[username]'");
echo $realpassword;
This will return a Resource which is used to point to the records in the database. What you then need to do is fetch the row where the resource is pointing. So, you do this (Note that I am going to use structural MySQLi instead of MySQL, because MySQL is deprecated now.)
$connection = mysqli_connect("localhost", "your_mysql_username",
"your_mysql_password", "your_mysql_database")
or die("There was an error");
foreach($_POST as $key=>$val) //this code will sanitize your inputs.
$_POST[$key] = mysqli_real_escape_string($connection, $val);
$result = mysqli_query($connection, "what_ever_my_query_is")
or die("There was an error");
//since you should only get one row here, I'm not going to loop over the result.
//However, if you are getting more than one rows, you might have to loop.
$dataRow = mysqli_fetch_array($result);
$realpassword = $dataRow['password'];
echo $realpassword;
So, this will take care of retrieving the password. But then you have more inherent problems. You are not sanitizing your inputs, and probably not even storing the hashed password in the database. If you are starting out in PHP and MySQL, you should really look into these things.
Edit : If you are only looking to create a login system, then you don't need to retrieve the password from the database. The query is pretty simple in that case.
$pass = sha1($_POST['Password']);
$selQ = "select * from accounts
where username = '$_POST[Username]'
and password = '$pass'";
$result = mysqli_query($connection, $selQ);
if(mysqli_num_rows($result) == 1) {
//log the user in
}
else {
//authentication failed
}
Logically speaking, the only way the user can log in is if the username and password both match. So, there will only be exactly 1 row for the username and password. That's exactly what we are checking here.
By seeing this question we can understand you are very very new to programming.So i requesting you to go thru this link http://php.net/manual/en/function.mysql-fetch-assoc.php
I am adding comment to each line below
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1"; // This is query
$result = mysql_query($sql); // This is how to execute query
if (!$result) { //if the query is not successfully executed
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) { // if the query is successfully executed, check how many rows it returned
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) { //fetch the data from table as rows
echo $row["userid"]; //echoing each column
echo $row["fullname"];
echo $row["userstatus"];
}
hope it helps
try this
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = mysql_real_escape_string($_POST['username']);
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
$row = mysql_fetch_array($new) ;
echo $row['password'];
if (!$new)
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
<?php
$query = "SELECT password_field_name FROM UsersTableName WHERE username_field_name =".$_POST['username'];
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row['password_field_name'];
?>
$username = $_POST['username'];
$login_query = "SELECT password FROM users_info WHERE users_info.username ='$username'";
$password = mysql_result($result,0,'password');

Categories