How to do a simple mysqli query for a similar value? - php

I am looking for just a basic query using mysqli to search table for a particular value. For example; If 'a' exist in a table then echo 'already exists'.
Please help as I am still learning to move away from deprecated code.
$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');
$result = $mysqli->query('select * from project');
if ($result)
{
$check = array();
while ($row = $result->fetch_assoc())
{
$check[] = $row['projectname'];
}
}
$a = 'a';
if ($a = $check)
{
echo "<script type='text/jscript'>
alert('already exists.')
</script>";
}

Databases are designed to do searching for you with WHERE clauses. There's no need to read the entire table when you can let the database do it for you.
$result = $mysqli->query("SELECT COUNT(*) AS found FROM project WHERE projectname = '$a'");
$row = $result->fetch_assoc();
if ($row['found'] > 0) {
echo "<script type='text/jscript'>alert('already exists.')</script>";
}

$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');
$result = $mysqli->query("select * from project where projectName = 'a'");
if($result->num_rows > 0)
echo "already exists";

You have a logic error in your code. You try to compare array ($check) with string ($a). Try something like this:
$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');
$result = $mysqli->query('select * from project');
if ($result) {
$check = array();
while ($row = $result->fetch_assoc()) {
$projectname = $row['projectname'];
if($projectname == 'a')
{
echo "<script type='text/jscript'>alert('already exists.')</script>";
break;
}
$check[] = $row['projectname'];
}
print_r($check);
}
else
{
echo "<script type='text/jscript'>alert('mysqli error')</script>";
}
This code will check every projectname in your table and will show alert if it exists projectname = 'a'.
P.s. If you want to contact with your database in really good way read about PDO driver (http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html)

Related

Using transactions in PHP and MySQL

I'm a learner of PHP. This commit and rollback process does the task at each line. How can I commit and rollback all at once?
<?php
$con = mysql_connect('localhost','user', 'abcdefg');
if(!con)
{
echo "Can't connect to db.";
}else {
mysql_select_db('test');
}
if(!file_exits('test.csv')
{
echo "Can't find the file.";
}
$ar_1 = file('test.csv', FILE_IGNORE_NEW_LINES);
foreach ($ar_1 as $ar1)
{
$test = explode(",", $ar1);
$sql = "SELECT * FROM DB WHERE CD = '$test[0]'";
$result = mysql_query_($sql);
$sql = "INSERT INTO DB(CODE) VALUES ('$test[0]');";
$result = mysql_query($sql);
if($result === true)
{
//Commit
$sql = "commit";
mysql_query($sql);
echo "Committed";
}else {
//Rollback
$sql = "rollback";
mysql_query($sql);
echo "Rollback";
}
}
mysql_close($con);
?>
you need to commit out of the loop, i used $bool to see if there somewhere the $result isn't true
it will look something like :
edit:
breaking from the loop when something is wrong as you don't need to continue looping to other elements.
$bool = 1;
foreach ($ar_1 as $ar1)
{
$test = explode(",", $ar1);
$sql = "SELECT * FROM DB WHERE CD = '$test[0]'";
$result = mysql_query_($sql);
$sql = "INSERT INTO DB(CODE) VALUES ('$test[0]');";
$result = mysql_query($sql);
if($result === false)
{
//Rollback
$bool = 0;
$sql = "rollback";
mysql_query($sql);
echo "Rollback";
break;
}
}
if($bool == 1)
{
//Commit
$sql = "commit";
mysql_query($sql);
echo "Committed";
}
mysql_close($con);

How to get an array instead of json object?

<?php
$link = mysql_connect('localhost', 'root', 'admin')
or die('There was a problem connecting to the database.');
mysql_select_db('hospitalmaster');
$hnum = (int)$_POST["hnum"];
$sql = "SELECT d.doctorid, d.doctorname
from hospitalmaster.doctor_master d
inner join pharmacymaster.pharbill e
where e.hnum = '$hnum'
and e.presid = d.d_empno
group by e.presid";
$result = mysql_query($sql);
$response = array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$response = $row;
}
echo json_encode(array("Doctor"=>$response));
} else {
echo ("no DATA");
}
?>
i have the api shown above, but this api is returning me as json objects not an json array? i would like to know how to get dotorid an doctorname as a array, since i have many doctor names and id, i want each doctor and their corresponding id as an idividual array, right now they are returning as individual objects. Since this is my first time writing an api, i dont know how to modify the code.
You are over writing the array each time round the loop.
while ($row = mysql_fetch_assoc($result)) {
$response[] = $row;
//change ^^
}
You should use either mysqli_ or PDO. Here is a suggestion for mysqli_
<?php
$link = mysqli_connect('localhost', 'root', 'admin','hospitalmaster')
or die('There was a problem connecting to the database.');
$sql = "SELECT d.doctorid, d.doctorname
from hospitalmaster.doctor_master d
inner join pharmacymaster.pharbill e
where e.hnum = ?
and e.presid = d.d_empno
group by e.presid";
$stmt = $link->prepare($sql);
$stmt->bind_param('i', (int)$_POST["hnum"]);
$stmt->execute();
if ($stmt->num_rows() > 0) {
$result = $stmt->get_result();
$response = array();
while ($row = $result->fetch_assoc()) {
$response[] = $row;
}
echo json_encode(array("Doctor"=>$response));
} else {
echo ("no DATA");
}
?>

PHP MySQLi if ID = 1 echo name from row

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);

PDO Search Engine?

I created a search feature for my website prior to me rewriting in PDO. I'm incredibly new to both PHP and PDO for use with a MySQL database, and I cannot for the life of me figure out how to translate this code, to PDO. I would appreciate someone talking me through it slightly, to help me learn.
My current code is:
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'";
$query = mysqli_query($connect, $sql);
$count = mysqli_num_rows($query);
if($count == 0) {
$output = '<tr><tr>No results found.</tr></td>';
} else {
while($row = mysqli_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td>'.$eName.'</td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}
return $output;
}
}
A PDO connection has been made, and it appears to be successful. This is in my functions.php file, and my connection.php file has been attached to functions.php.
Thanks in advance!
It should be something like
$conn='';
try {
$conn = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
}
catch (PDOException $e) {
exit('Database error.');
}
$sql = "SELECT * FROM entries WHERE name LIKE :searchq or description LIKE :searchq or content LIKE :searchq";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchq",$searchq,PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 0) {
$output = '<tr><tr>No results found.</tr></td>';
} else {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td>'.$eName.'</td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}

Echo text only if MySQL value matches

I have two rows in my MySQL data that I would like to have code echoed only if the MySQL row data is equal to '1' (as opposed to '0'). Here's the code so far, which seems to have some severe errors:
$query = "SELECT 162, 164 FROM search WHERE title = $title";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
if ($row["162"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
if ($row["164"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
}
$result->close();
}
$mysqli->close();
As it says in the code above the two rows are "162" and "164" in the database.
Use:
if ($row["162"] == 1)
Instead of:
if ($row["162"] = 1)
and:
if ($row["164"] == 1)
I tried for you something like this if it gives you some idea:
$host = "localhost";
$user = "myusername";
$pass = "mypassword";
$database = "WorldEngine";
$mysqli = new mysqli($host, $user, $pass, $database);
$title = "My Good News";
$query = "SELECT `162`, `164` FROM search WHERE title = '$title';";
if ($result = $mysqli->query($query)) {
$i = 0;
while ($row = $result->fetch_row()) {
if ($row["162"] == 1) {
echo '<div id="162link' . $i . '">1.6.2</div>';
}
if ($row["164"] == 1) {
echo '<div id="164link' . $i . '">1.6.4</div>';
}
$i++;
}
$result->free();
}
$mysqli->close();
The index $i is appended to the div ID in order to produce unique DOM element ID's in the HTML document. I would also suggest you to change your numerical column names into alphabet-starting names like c162, c164, ...
Hope this will help you.

Categories