Mysql - Seeing if a value already exist - php

i just want to know how I can fix this. In my database : here i have a value of 123. My code is searching for it however it does not find it.
<html>
<head>
<?php
$userid = 123;
$con = mysqli_connect("","","*","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo "Connected";
}
echo "123";
// Perform queries
$sql_fetch_id = "SELECT * FROM AccessedIds WHERE 64id = '123";
$query_id = mysqli_query(sql2242953, $sql_fetch_id);
if(mysqli_num_rows($query_id) ==0) {
echo "empty";
}else{
echo "full";
}
mysqli_close($con);
?>
<title>PHP Test</title>
</head>
<body>
</body>
</html>
Data types

Your query is wrong, try:
$query_id = mysqli_query($con, $sql_fetch_id);
More information
Also as in the comments above, remove the single quote mark before 123.

Your Query and Query string is wrong. You are missing a Single Quote (') in your Query string. See the below statements:
$sql_fetch_id = "SELECT * FROM `AccessedIds` WHERE `64id` = '123'";
$query_id = mysqli_query($con, $sql_fetch_id);
Hope this helps.

Related

Trouble retrieving data with PHP and SQL

I'm struggling to retrieve data from a table holding basic information. I've tried to use odbc_fetch functions but I couldn't get them to work. Could someone show me how to retrieve the data from a certain row
<?php
session_start();
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<?php
$employeeNumber = $_SESSION["user"];
$connect=odbc_connect("CoveringSystem", "", "");
$getData="SELECT FirstName, LastName FROM Details WHERE EmployeeNumber ='$employeeNumber'";
$result = odbc_exec($connect, $getData);
## //I've tried to add the odbc_fetch functions here\\ ##
echo $employeeNumber;
echo $firstName;
echo $lastName;
?>
</body>
</html>
Check this with mysqli :
// First connect to database
$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();
}
// Than make your query
$getData=mysqli_query($con,"SELECT FirstName, LastName FROM Details WHERE EmployeeNumber ='$employeeNumber'");
//Count row returned
if(mysqli_num_rows($getData)>0){
while($row=mysqli_fetch_assoc($getData)){
$firstName=$row['FirstName'];
$lastName=$row['LastName'];
//then you can do whatever you like with your data
}
}else{
}

PHP mySQLi query returning data but not displaying it

Good day,
I have done extensive research on this issue but unfortunately none of the related issues solved my problem.
Here I have a very basic PHP mySQLi db connection. The connection succeeds and so does the query that is run on the table. The issue is that the the result set will not display. All of my references are correct and when I check to see if the result set is populated, it is. I believe the issue is with my while block but no errors are returned when this is run.
Thank you for your time
<?php
$db = mysqli_connect('localhost','root','','securitour') //connection to the database
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT * FROM location"; //The SQL query
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query); //query the table an store the result set in a variable
$row = mysqli_fetch_array($result); //create an array and store the records of the result set in it
if (mysqli_num_rows($result) != 0) //to check if the result set contains data
{
echo "results found"; //THIS is what is returned.
}
else
{
echo "results not found";
}
while ($row = $result->fetch_assoc()) //itterate through the array and display the name column of each record
{
echo $row['name'];
}
mysqli_close($db);
?>
</body>
</html>
Lots of things not right here.
You are processing the mysqli_query() function twice - there is no need.
You are selecting all fields in your SQL query (SELECT *). You should select fields by name.
You're interchanging between procedure and class-based MySQLi - You should stick to one or the other.
Try this instead:
<?php
$db = mysqli_connect('localhost','root','','securitour') //connection to the database
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT name FROM location"; //The SQL query
$result = mysqli_query($db, $query) or die('Error querying database'); //query the table an store the result set in a variable
if(mysqli_num_rows($result) > 0){
echo "Results found!";
while($row = mysqli_fetch_array($result)){ //create an array and store the records of the result set in it
echo $row['name'];
}
} else {
echo "results not found";
}
mysqli_close($db);
?>
</body>
</html>
You don't need to run mysqli_query() twice. and you need to use mysqli_fetch_assoc for associative array
<?php
$db = mysqli_connect('localhost','root','','securitour') or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT * FROM location"; //The SQL query
$result = mysqli_query($db, $query) or die('Error querying database.'); //query the table an store the result set in a variable
$row = mysqli_fetch_assoc($result); //create an array and store the records of the result set in it
if (mysqli_num_rows($result) != 0) //to check if the result set contains data
{
echo "results found"; //THIS is what is returned.
} else {
echo "results not found";
}
foreach ( $row as $name=>$val) {
echo $name . ':' . $val . '<br>';
}
mysqli_close($db);
?>
</body>
</html>

PHP - Create check box by using the records from MySQL datebase as values

i am a newbie in php programming and i cant figure out where i have gone wrong as my php code wont execute.
As the title says i am trying to create check boxes in my site however the values will come from the mysql database.
I have a table named “campus” in MySQL database and it has 2 coloumns called id and room.
database
[![Database][1]][1]
http://i.imgur.com/uLP6niJ.png
current output
[![Current Output][2]][2]
http://i.imgur.com/cSOYPme.png
below is my code:
<?PHP
$hostname = "localhost";
$username = "root";
$password = "root";
$databaseName = "my computer";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$s = '';
$j = 0;
if ($q = $connect->query("SELECT * FROM `campus`")) {
while ($line = $q->fetch_assoc()) {
$s.= '<input type="checkbox" name="car'.$j.'" value="'.$line['room'].'">';
}
}
echo $s;
?>
</form>
</body>
</html>
You're not closing the while loop properly. Close the while loop as follow.
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="checkbox" name="car" value="<?php echo $line['room']?>" />
<?php
}
?>
Welcome to PHP!
An error is that you're missing the semicolon that's needed after any php function (such as echo)
<?php echo $line['room']; ?>
And there's the missing PHP tags around the closing }
A third error is that you're not telling mysqli which connection to run the query on it should have:
mysqli_query($dbCon, $sql);
Apart from that it looks good, personally I prefer to use a PDO connection but mysqli is still good, but there are a few formatting tricks that can help prevent problems.
For example it's always a good idea to use back-ticks (`)
So:
$sql = "SELECT `room` FROM `campus`";
However, for this it might be best to use the * query. Which selects everything from the column so:
$sql = "SELECT * FROM `campus`";
The reason is how you're getting the data, you're telling PHP to create an array using the results.. but you've only given it one piece of data for each row. So if you give it all of the data it just makes it a little easier to use.
Here's the full code:
<?php $dbCon = mysqli_connect("localhost", "root", "root", "my computer");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$sql = "SELECT * FROM `campus`";
$result = mysqli_query($dbCon, $sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) { ?>
<input type="checkbox" name="car" value="<?php echo $line['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Also, if you're interested, here's how it'd be done in PDO:
<?php
try{
$con = new \PDO("mysql:host=" . 'localhost' . ";dbname=" . 'My Computer', 'root', 'root');
}catch(PDOException $e){
echo "Connection Failed";
die();
} ?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$result = $con->prepare("SELECT * FROM `campus`")
$result->execute();
while ($row = $result->fetch()) { ?>
<input type="checkbox" name="car" value="<?php echo $row['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Still not working? Feel free to comment and I'll see what's up :)
Thanks,
P110
Try with this
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
$campusArray = mysqli_fetch_array($result, MYSQLI_ASSOC);
foreach ($campusArray as $campus): ?>
<input type="checkbox" name="car" value="<?php echo $campus['room'];?>" />
<?php endforeach; ?>
I hope with this you can solve your problem.
alternative syntax is excellent for improving legibility (for both PHP
and HTML!) in situations where you have a mix of them.
http://ca3.php.net/manual/en/control-structures.alternative-syntax.php

How to show a database colum data on my php script?

I have a php script made by me that can change a database info by taking db name,user,pass and host. Now I want to show a database column info to my php script.
Now how can i do that here is my main db.php script i didn't put the html from script cause i don't think it's necessary.
I have code this but it's showing a error like that
Parse error: syntax error, unexpected T_STRING in /home/abc/public_html/db.php on line 56
Here is my db.php
<style type="text/css">
body {
background-image: url('data:image/gif;base64,R0lGODlhAwADAPcAAAAAAABCAP///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////ywAAAAAAwADAAAICQADABhIcGBAAAA7');
font-family: Tahoma;text-align: center;color: green;
}
img{opacity:0.75; filter:alpha(opacity=75);}
.field_set{
border-color:#4AB825;
}
</style>
<?php
// escape received values
$dbusr = $_POST['usr'];
$dbpsw = $_POST['psw'];
$dbhost = $_POST['host'];
$dbname = $_POST['dbname'];
$admusr = $_POST['admusr'];
$prfx = $_POST['prfx'];
$admpsw = md5($_POST['admpsw']);
// Create connection
$conn = new mysqli($dbhost, $dbusr, $dbpsw);
// Check connection
if ($conn->connect_error) {
die("<br><br><br><br><br><br><br>Database Connection failed: " . $conn->connect_error);
}
echo "<br><br><br><br><br><br><br>Database Connected successfully";
mysqli_select_db($conn,"$dbname");
// use them in query
$sql = "UPDATE ".$prfx."_users SET user_login='".$admusr."',user_pass='".$admpsw."' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "<br><br>Record updated successfully</br></br>Go to your login page <br><br>ex: www.site.com/wp-admin<br><br>and login with your given id and pass";
} else {
echo "<br>Error updating record:" . $conn->error;
}
$sql = "SELECT guid FROM".$prfx."_posts;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Site:" . $row["guid"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
$sql = "SELECT guid FROM".$prfx."_posts;
Should be
$sql = "SELECT guid FROM".$prfx."_posts";
You were missing the closing "
As Dagon said in his comment, In most editors code is shown with color coding, and you can usually see if a " or ' is missing it's closing tag because the color will be off.
UPDATE
Missing space between FROM and $prfx, use below:
$sql = "SELECT guid FROM ".$prfx."_posts";
You are missing a " at the end of line try replace this.
$sql = "SELECT guid FROM".$prfx."_posts";
Whenever you get this error it means that you are missing a closing double quote on that line which is mentioned on the error.
Change this,
$sql = "SELECT guid FROM".$prfx."_posts;
to this,
$sql = "SELECT guid FROM".$prfx."_posts";

Simple php/sql search engine

I am trying to make a simple php, sql search engine that will select everything from my database that is "LIKE" the keyword (query) and display it. However it will not work. It only displays the text "problem"(see line 32) and after hours of troubleshooting I still can not figure this out.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Search Engine Test</title>
</head>
<body>
<script language="php">
// Create a database connection
$connection = mysql_connect("*****","*****","*****");
if (!connection) {
die ("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("*****",$connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
// Search Engine
// Only execute when button is pressed
if (isset($_POST['search'])) {
// Filter
//$keyword = trim ($keyword);
echo $keyword;
// Select statement
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
$result = #mysql_query($search);
if (!$result){
echo "problem";
exit();
}
while($result = mysql_fetch_array( $search ))
{
echo $result['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($search);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
</script>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="keyword">
<input type="submit" name="search" value="Search">
</body>
</html>
Try and change:
if (isset($_POST['search'])) { //$_POST['search'] just tells that there are a submit-button when submitting (and the name of it)
// Filter
//$keyword = trim ($keyword);
echo $keyword; //You're echoing out value of $keyword which hasn't been set/assigned
// Select statement
//You're always searching for the word keyword with leading and/or trailing characters
//You're not searching for a dynamically assigned value which I think is what you want
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
//You're executing an already defined query (assigned in $search)
$result = #mysql_query($search); //You're suppressing errors, it's bad practice.
if (!$result){
echo "problem";
exit();
}
to:
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim ($_POST['keyword']);
// Select statement
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%$keyword%'";
// Display
$result = mysql_query($search) or die('query did not work');
IMPORTANT!
<script language="php"> isn't valid. You should type <?php at the beginning of php-code and ?> to end php-code.
UPDATE:
You will also have to change this code:
while($result = mysql_fetch_array( $search ))
{
echo $result['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($search);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
TO:
while($result_arr = mysql_fetch_array( $result ))
{
echo $result_arr['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($result);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
When making new code, you really should NOT use mysql_ functions*, because they're deprecated. Look into PDO or mysqli instead.
Expanding your code, we can see that:
$result = #mysql_query($search);
turns into:
$result = #mysql_query(mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'"));
Which doesn't make much sense.
Change the first line to:
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'"
or, instead of assigning $search a value at all, just skip to assigning $result the value that $search currently has.
EDIT: to help you explain:
Change this:
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
$result = #mysql_query($search);
if (!$result){
echo "problem";
exit();
}
to this:
$result = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
if (!$result){
echo "problem";
exit();
}

Categories