Getting php variable to select statement not working - php

Here i am trying to pass the variable to php select query,but its not working.
couldn't figure out what is the problem.
code:
<?php
$cname = $_GET['c_name'];
include 'config.php';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM co_details where co_name="$cname"';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<br>";
echo "Course Details <br>";
echo $row['co_name']."<br>";
echo $row['co_objectives']."<br>";
echo $row['co_outline']."<br>";
echo $row['co_prereq']."<br>";
echo $row['co_fee']."<br>";
echo $row['co_duration']."<br>";
}
mysqli_close($conn);
}
?>
what may be the reason?
Instead of variable $cname if i put the direct value then the query is executing successfully.

Note that single quoted strings like this one you have:
$sql = 'SELECT * FROM co_details where co_name="$cname"';
That variable that you think you have there will not get interpolated. It will only work by using double quoted strings.
$sql = "SELECT * FROM co_details where co_name='$cname'";
And as #Fred has said in the comments, stick with MySQLi including your connection error:
if(! $conn )
{
die('Could not connect: ' . mysql_error()); // mysql API doesn't belong
}
Change it to MySQLi interface:
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
And you should have used prepared statements instead as this is prone to SQL injection.
<?php
if(!empty($_GET['c_name'])) {
$cname = $_GET['c_name'];
include 'config.php';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
$sql = 'SELECT co_name, co_objectives, co_outline, co_prereq, co_fee, co_duration FROM co_details WHERE co_name = ?';
$select = $conn->prepare($sql);
$select->bind_param('s', $cname);
$select->execute();
$select->store_result();
$select->bind_result($co_name, $co_objectives, $co_outline, $co_prereq, $co_fee, $co_duration);
while($select->fetch()) {
echo "<br/>
Course Details: <br/>
$co_name <br/>
$co_objectives <br/>
$co_outline <br/>
$co_prereq <br/>
$co_fee <br/>
$co_duration <hr/>
";
}
}
?>

You can't use $cname directly in the string: try as shown below:
$sql = "SELECT * FROM co_details where co_name='".$cname."'";
Hope, it helps!

You are using single quote don't do like that change the query like this
$sql = "SELECT * FROM co_details where co_name='$cname'";

Related

PHP and SQL -- Select from database

I have a problem with this code. It has syntax error and I don't know what is it.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
echo $sql;
?>
There are some issue with the code. First you forgot to close the if condition over here
if (!$conn) {
And then you forgot to execute the sql query
the complete code would be like
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
if ($result = $conn->query($sql)) {
while ( $row = $result->fetch_assoc()) {
$data[] = $row;
}
echo "<pre>";
print_r($data);
echo "</pre>";
}
$conn->close();
?>
There are two errors
You are missing } closing bracket after die
Mysql query is wrong.
So the code should be
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email="donat12#icloud.com"';
echo $sql;

Basic PHP entry failing

I'm setting up a wedding invitation RSVP form. I have here what should be a basic PHP and SQL data entry, but I keep getting the error:
"Could not enter data: No database selected"
UPDATE - Many thanks to all your suggestions. I have updated my code as you can see bellow. I now get a new error as follows:
"Could not connect:" (witch is a message I output myself in line 7, but it does not show the error that should follow")
Does anyone know what this means please?
Here is my [UPDATED] code:
<?php
function submit(){
$con = mysqli_connect("localhost", "jaredand_rsvp", "jar3dandcr1st1na", "jaredand_rsvp");
if (!$con)
{
die('Could not connect: ' . $con->error);
}
$name = $_POST['name'];
$partnerName = $_POST['partner_name'];
$allergies = $_POST['allergies'];
$comments = $_POST['comment'];
$going = $_POST['going'];
$sql = 'INSERT INTO rsvp '.
'(name,partner_name, allergies, comments, going) '.
'VALUES ( "'.$name.'", "'.$partnerName.'", "'.$allergies.'", "'.$comments.'", "'.$going.'")';
$result = $con->query($sql);
if(!$result )
{
die('Could not enter data: ' . $result->error);
}
echo "Entered data successfully\n";
mysqli_close($con);
}
if(isset($_POST['name']))
{
submit();
}
?>
Can anyone please advise me on what I am doing incorrectly?
That happens because mysql_connect doesn't have database name as parameter.
You should connect to the server, and then select a database by calling mysql_select_db
Cheers!
this is the right way
$con = mysql_connect("localhost","USERNAME","PASSWORD);
mysql_select_db('jaredand_rsvp', $con);
but please use "mysqli"
$con = mysqli_connect("localhost", "USERNAME", "PASSWORD, "jaredand_rsvp");
$result = $con->query($sql);
happy to help,
for security is better if you escape your values before insert :
$name = $con->real_escape_string($_POST['name']);
$partnerName = $con->real_escape_string($_POST['partner_name']);
$allergies = $con->real_escape_string($_POST['allergies']);
$comments = $con->real_escape_string($_POST['comment']);
$going = $con->real_escape_string($_POST['going']);
Try to connect to the database first and then select the database name
I hope this will fix your issue
Or you could use PDO because mysql_connect is depricated
You have used $con = mysql_connect(); at the top and bottom you are using:
mysqli_close();
First follow the same standarad. Use mysqli instead of sqli at top.i.e,
$con = mysqli_connect("localhost","USERNAME","PASSWORD", "jaredand_rsvp");
Remove the line: mysql_select_db('jaredand_rsvp');
and replace $retval = mysql_query( $sql, $con ); with
$retval = mysqli_query( $sql, $con );
Use it another Way
<?php
function submit() {
$host = "localhost";
$username = "root";
$password = "";
$dbname = "jaredand_rsvp";
$con = new mysqli($host, $username, $password, $dbname);
if ($conn -> connect_error) {
die("Connection failed: " . $conn -> connect_error);
}
$name = $_POST['name'];
$partnerName = $_POST['partner_name'];
$allergies = $_POST['allergies'];
$comments = $_POST['comment'];
$going = $_POST['going'];
$sql = 'INSERT INTO rsvp ' . '(name,partner_name, allergies, comments, going) ' . 'VALUES ( "' . $name . '", "' . $partnerName . '", "' . $allergies . '", "' . $comments . '", "' . $going . '")';
if($con->query($sql)== TRUE){
echo "Data Inserted";
}
else {
echo mysqli_error($con);
}
mysqli_close($con);
}
if (isset($_POST['name'])) {
submit();
}
?>
How about using MySQLi instead of the now depreciated MySQL?
EDIT
Okay, I see no connection being made to the database. Something like
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
If you have stored the db connect credential on a different file then i see no include or require mentioned on your this script either. Check if you have made the connection and then get back.

PHP/MySQL echo links

I've looked all over Google for some examples of this, but I just can't seem to find a solution! Either they're going for an internal URL (with a dynamic ID pointing to a page, etc.) Basically all the other questions are about links that are more complex than what I'm going for.
Basically I have a table with 2 fields - name, and URL. (the page is a secret santa page where users can share their Amazon wish lists and view other users lists)
I want the URL to echo a link to the proper amazon wishlist URL.. here's my code:
<?php
$dbhost = 'localhost:post';
$dbuser = 'db_user';
$dbpass = 'db_pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT name, url FROM santa';
mysql_select_db('rev_phoenix');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "<b>Username:</b> {$row['name']} <br> ".
"<b>Wishlist:</b> {$row['url']} <br> ".
"<hr>";
}
echo "Merry Christmas!\n";
mysql_close($conn);
?>
As far as I'm aware, mysql has been depricated as of PHP 5.5.0
You may want to go with using mysqli
Try using this for your code:
<?php
$dbhost = 'localhost:post';
$dbuser = 'db_user';
$dbpass = 'db_pass';
$dbcurrent = 'rev_phoenix';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbcurrent);
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
//Added order by random, and limit 1 to only show 1 'secret' santa.
$sql = 'SELECT name, url FROM santa ORDER BY RAND() LIMIT 1';
$retval = mysqli_query( $sql, $conn );
if(! $retval ) {
die( 'Could not get data: ' . mysqli_error($conn) );
}
while($row = mysqli_fetch_assoc($retval) {
echo "<b>Username:</b> ". $row['name'] . "<br> ".
"<b>Wishlist:</b> <a href='" . $row['url'] . "'>List</a><br>".
"<hr>";
}
echo "Merry Christmas!\n";
mysqli_close($conn);
?>

Why can't i echo my results from MySQL in PHP?

I try to show every result that the current username has in the database,
but it won't work..
I've tried anything and ya'll are my last hope.
Thanks in advance!
I can not get any answer from my code here below:
<?php
session_start();
include_once('../inc/db/config.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT serverip, servername FROM servers WHERE username=".$_SESSION['user_name']."";
$results = mysqli_query($mysqli, $query);
if(mysqli_num_rows($results) >= 1)
{
while($row = mysqli_fetch_array($results))
{
echo "<hr/>";
echo "<a href='../s_info.php?server='" . $row['serverip'] . "><h2>" . $row['servername'] . "</h2>";
}
}
?>
This line looks suspect to me:
$query = "SELECT serverip, servername FROM servers WHERE username=".$_SESSION['user_name']."";
Try:
$query = "SELECT serverip, servername FROM servers WHERE username='{$_SESSION['user_name']}'";
You should be able to echo out that string as a test and run it separately in mysql command line/phpMyAdmin or whatever tool allows you to test sql statements. Insure that it returns a result.

Mysqli wont allow table's to show when called on

As of recently ive been learning php and at that conjuntion in between where i have to now use Mysql in order to keep my bigger info table ogranized, well i wrote this code in order to show the tables (or so i think i did it right). im completely stumped because i can not see any of the displaying tables that i am calling on and the more ive tried the less i works so i was wondering if anyone can see a loop hole in my code or maybe im doing something wrong? or maybe everything ive done is wrong...?
`
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
?>
<?php
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<ul>
<?php
while($subject = mysqli_fetch_assoc($result)) {
?>
<li><?php echo $subject["menu_name"] . "(" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result);
?>
</body>
</html>
<?php
mysqli_close($connection);
?>`
Have you forgotten the opening PHP tag at the beginning of your page?
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
Two things i think could be wrong.
Here is a correct implementation to compare. It could be the first PHP opening tag, i also added the default port to the connect statement, and added some try catches with error messages, these can tell if the connect or query is not working.
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
//original connect statement with a port added in
try {
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname , 3306);
} catch(Exception $e) { echo $e->getMessage(); }
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Query looks fine, easier to trouble shoot when its one line, first get it working then break it up
$query = "SELECT * FROM subjects WHERE visible = 1 ORDER BY position ASC";
// This will try to fetch the result and give an error if it can't.
try { $result = mysqli_query($connection, $query);
} catch(Exception $e) { echo $e->getMessage(); }
if (!$result) { die("Database query failed"); }
?>
Is it alright if I alter some of your codes?
See this:
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION */
$connection=mysqli_connect("localhost","juliegri_AAlassa","YourPassword","juliegri_Aalassaly");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* START QUERY */
$result=mysqli_query($connection,"SELECT * FROM subjects WHERE visible='1' ORDER BY position ASC");
?>
<ul>
<?php
/* DO THE WHILE LOOP */
while($subject = mysqli_fetch_array($result)) {
?>
<li><?php echo $subject['menu_name'] . "(" . $subject['id'] . ")"; ?></li>
<?php
} /* END OF WHILE LOOP */
?>
</ul>
</body>
</html>

Categories