Check for specific entry in database - php

I want to check whether a specific entry is present in my database or not. If present then condition,if not then condition. I tried this code but got errors
<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysql_query("SELECT * FROM subjectinfo WHERE class = '{$classname}'", $con);
if(mysql_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
Errors :
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\xampp\htdocs\pages\test.php on line 11
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\xampp\htdocs\pages\test.php on line 13
No Such Entry In Table. Please ADD it First.

Like your comments. Make sure you don't mix up mysqli and mysql. mysql is deprecated so you're better off using mysqli.
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysqli_query($con, "SELECT * FROM subjectinfo WHERE class = '{$classname}'");
if(mysqli_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>

You are mixing MySQL APIs - mysql_ + mysqli_ they do not mix together. Plus, your DB connection's backwards in your query. The connection comes first.
Here:
<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysqli_query($con,"SELECT * FROM subjectinfo WHERE class = '{$classname}'");
if(mysqli_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
Also use or die(mysqli_error($con)) to mysqli_query()
Plus, add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Look into using prepared statements, or PDO with prepared statements, they're safer.
An insight:
Make sure your form element is indeed named.
I.e.:
<input type="text" name="class">
otherwise, you will receive an Undefined index class... warning.

Related

Checking whether username exists in MySQLi Database and PHP

I have been working on a website which has a xampp server and a database called users with a table called AccountDetails. About a year ago I got it to work perfectly, but the server I was using then required MySQL not MySQLi. Now I have to use MySQLi and can't even get the simplest of sql's SELECT function to work, any ideas would be much appreciated.
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$result = $link->query("SELECT ID, UserName FROM AccountDetails");
return $result->result();
var_dump($result);
mysqli_close($link);
?>
The Query itself works when I plug it into the phpmyadmin SQL section and it returns the values that I expect it too.
I've spent days looking online for different answers but none of them work, and the var_dump only gives me "bool(false)" which I don't think I should be getting.
You can try this code
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$sql_select = "SELECT * FROM AccountDetails";
$result = $link->query($sql_select);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "UserName: " . $row['UserName']. "<br>";
}
} else {
echo "No Records";
}
$link->close();
?>

MYSQL assign column name to variable?

I have a database table which has two columns, business and tourist.
I ask a user to select one of them from dropdown list, then use the result in a SELECT statement in MySQL. I assign this column to $cclass, then I make this statement SELECT $cclass FROM flights ....
But it always returns NULL. Why does it return NULL and how do I fix this?
My code:
$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");
while ($result = mysql_fetch_assoc($check))
{
$db_seats = $result['$cclass'];
}
you should replace this line:
$db_seats = $result['$cclass'];
with this:
$db_seats = $result[$cclass];
string between 2 single quotes doesn't parsed:
Strings
Have you tried doing the following:
$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");
First of all, this code has a serious security issue, as it is vulnerable to SQL Injection. You should be using the MySQLi extension instead, and properly filtering your input.
Try something like this:
<?php
/* Create the connection. */
$mysql = new mysqli("localhost", "username", "password", "myDB");
if ($mysql->connect_error)
{
error_log("Connection failed: " . $mysql->connect_error);
die("Connection failed: " . $mysql->connect_error);
}
/* Sanitize user input. */
if (!in_array($cclass, array('business', 'tourist')))
{
error_log("Invalid input: Must be 'business' or 'tourist'");
die("Invalid input: Must be 'business' or 'tourist'");
}
$statement = $mysql->stmt_init();
$statement->prepare("SELECT $cclass FROM flights WHERE flight_no = ?");
$statement->bind_param("s", $flightno);
if (!$statement->execute())
{
error_log("Query failed: " . $statement->error);
die("Query failed: " . $statement->error);
}
if ($statement->num_rows < 1)
{
echo "No results found.";
}
else
{
$statement->bind_result($seats);
while ($statement->fetch())
{
echo "Result: $seats";
// Continue to process the data... You can just use $seats.
}
}
$mysql->close();
However, the reason your original example is failing, is that you're quoting $cclass:
$db_seats = $result[$cclass];
However, please do not ignore the serious security risks noted above.

Warning: mysqli_query() expects parameter 2 to be string, object given in C:\wamp\www

when I try this code I receive warning about second parameter to string. I have seen some answers in previous similar questions but I did not find the solution... As far as I can get the problem is with if statement?? Thanks.
if (isset($_GET['id'])) {
$str_id = $_GET['id'];
($conn->set_charset("utf8"));
if ($result=mysqli_query($conn, $q )) {
while ($obj=mysqli_fetch_object($result)) {
}
?>
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
while ($obj=mysqli_fetch_object($result))
{
printf("%s (%s)\n",$obj->Lastname,$obj->Age);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>

Mysqli, stuck between "or die" and "sqlierror"

I'm having a trouble around starting a session. Here's my php:
<?php
session_start();
$con=mysqli_connect('localhost','root','','pttkhdt');
if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
else {
$a = $_SESSION['a'];
$knad ='SELECT * FROM admintb WHERE adID=' .$a;
$naad = mysqli_query($con,$knad);
$arad = array();
while($rowad=mysqli_fetch_assoc($naad)) $arad[] = $rowad;
}
?>
If I input that, when I tried to test run my site, it will show:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in...
But if I fix the line
$naad=mysqli_query($con,$knad);
Into:
$naad=mysqli_query($con,$knad) or die;
the page will "die" out and blank.
From the looks of it you're loading your mysqli_fetch_assoc into an array, using a while loop. However, a mysqli_fetch_assoc() is already loading an array.
Why don't you try this:
<?php
session_start();
$con=mysqli_connect('localhost','root','','pttkhdt');
if ( mysqli_errno($con) ) {
//Exit stops the rest of the script
exit( "Failed to connect to MySQL: " . mysqli_error($con) );
} else {
$a = $_SESSION['a'];
$knad = "SELECT * FROM admintb WHERE adID='" . $a . "'";
$arad = mysqli_fetch_assoc( mysqli_query($con,$knad) );
if (!$arad) { exit( mysqli_error($con) ); }
}
?>
The reason behind your sql error may be the fact that your prior SQL $knad statements says for example, adID=justatestvalue, so your SQL is searching for the column justatestvalue. Make sure to enclose actual statements in quotes.
mysqli_query($con,"SELECT * FROM user WHERE userName='$user'");
Check your error with mysql_error() and update your error here;
$naad=mysqli_query($con,$knad) or die(mysql_error());
or try this code below
$link=mysql_connect($host,$user,$pwd);
$db = mysql_select_db($dbname,$link);
if(!$db) die (mysql_error());

mysql_close() expects parameter 1 to be resource, null given

The line causing the error is this one...
mysql_close($con);
Here is the entirety of the code...
$con=mysqli_connect("localhost","root","pass","db_name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM medicos");
while($row = mysqli_fetch_array($result)) {
echo '.....';
}
mysql_close($con);
The line mysql_close($con); must be changed to mysqli_close($con);
You cannot interchangeably use mysql and mysqli functions, for example:
mysqli_connect requires use of mysqli_close
- likewise -
mysql_connect requires use of mysql_close

Categories