mysqli_query giving me unsolvable message - php

I am trying to make a basic song info page, and my only problem is the SQL. I keep getting this message:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in /var/www/tts/recommend-action.php on line 33
Here is my code:
<?php
session_start();
ini_set("display_errors",true);
ob_start();
$host = "localhost";
$user = "root";
$pass = "[MYPASSWORD]";
$db = "[MYDATABASE]";
$tb = "recommendation";
$link = mysqli_connect($host, $user, $pass, $db) or die("Failed to connect.");
$song = $_POST['song'];
$album = $_POST['album'];
$artist = $_POST['artist'];
$linkitunes = $_POST['linkitunes'];
$artwork = $_POST['albumPic'];
$song = stripslashes($song);
$album = stripslashes($album);
$artist = stripslashes($artist);
$link = stripslashes($linkitunes);
$artwork = stripslashes($artwork);
print "<br /><br /><b>User ID: </b>" . $_SESSION['user_id'] . "<br /><b>Song: </b>$song<br /><b>Album: </b>$album<br /><b>Artist: </b>$artist<br /><br />";
$sql = "INSERT INTO recommendation (user_id, artist, song, album, artwork, linkitunes) VALUES (" . $_SESSION['user_id'] . ", $artist, $song, $album, $artwork, $linkitunes);";
$postrec = mysqli_query($link, $sql);
if ($postrec == true) {
print "sucess";
}
else {
print "<br /><br />failed";
}
ob_flush();
?>
I cannot find a solution. Help is very greatly appreciated.

You connect fine and $link is good:
$link = mysqli_connect($host, $user, $pass, $db) or die("Failed to connect.");
But then later redefine as a string:
$link = stripslashes($linkitunes);
And then you try and use the string:
$postrec = mysqli_query($link, $sql);

Related

Inserting xml values in table no success

Trying to get my xml feed into a table, missing something as not working.
Warning: mysqli_query(): Couldn't fetch mysqli in
/Users/John/Sites/XMLproject/Update Emperor.php on line 77
//Database variables
$servername = "localhost";
$username = "Something";
$password = "Very secret";
$dbname = "TestDB";
$temptable = "wlbvx_jb_xml_emperor";
//Open database
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database: ","<strong>",$dbname,"</strong>","<br>" ;
?><br><?php
$url = "http://bookings.emperordivers.com/webScheduleSpecificXML_all.asp";
$feed = file_get_contents($url);
$xml = simplexml_load_string($feed);
//Row by row into variable, then into table
foreach ($xml->Schedule as $row) {
$ID = "Null";
$start = date("d-m-Y", strtotime($row->Start));
$duration = $row->Duration;
$boat = $row->Boat;
$itinerary = $row->Itinerary;
$spaces = $row->Spaces;
$rateseur = round(str_replace(',', '', $row->Rates->Rate[0]));
$rategbp = round(str_replace(',', '', $row->Rates->Rate[1]));
$rateusd = round(str_replace(',', '', $row->Rates->Rate[2]));
$sql = "INSERT INTO $temptable (id,xml_date, xml_duration, xml_boat, xml_itinerary, xml_spaces, xml_rate_eur, xml_rate_gbp, xml_rate_usd)VALUES ('{$ID}',{$start}', '{$duration}', '{$boat}', '{$itinerary}','{$spaces}', '{$rateseur}', '{$rategbp}', '{$rateusd}')";
echo "SQL Query to execute:",$sql,"<br>";
mysqli_query($conn, $sql);
}
What could cause the issue?

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 query alwaysfalse no matter what

I have tried to read and do (incorporate) anything I find on here. But I have not found the solution. I'm using wamp server and I have a user table with 2 users one with email and password as test and test1 and no matter what I try the if statement always returns false.
<?php
$user = "root";
$pass = "";
$db = "testdb";
$db = new mysqli("localhost", $user, $pass, $db) or die("did not work");
echo "it connected";
$email = "test";
$pass1 = "test1";
$qry = 'SELECT * FROM user WHERE email = " '. $email .' " AND password = " '.$pass1.' " ';
$result = mysqli_query($db, $qry) or die(" did not query");
$count = mysqli_num_rows($result);
if( $count > 0)
echo " found user ";
else
echo " did not find user or password";
?>
I have tried to augment mysqli_num_rows but then it comes out always true
You have spaces in your query around your variables:
" '. $email .' "
change to:
"'. $email .'"
MySQL will take those spaces literally when it searches for matches.
I needed to eliminate the blank spaces in the encapsulation of the variable
<?php
$user = "root";
$pass = "";
$db = "testdb";
$db = new mysqli("localhost", $user, $pass, $db) or die("did not work");
echo "it connected";
$email = "test";
$pass1 = "test1";
$qry = 'SELECT * FROM user WHERE email = "'. $email .'" AND password = "'.$pass1.'"';
$result = mysqli_query($db, $qry) or die(" did not query");
$count = mysqli_num_rows($result);
if( $count > 0)
echo " found user ";
else
echo " did not find user or password";
?>
If you are using mysqli class version then you should use like below :
<?php
$user = "root";
$pass = "";
$db = "testdb";
$mysqli = new mysqli("localhost", $user, $pass, $db);
$email = "test";
$pass1 = "test1";
$qry = sprintf('SELECT * FROM user WHERE email = "%s" AND password = "%s"',$email,$pass1);
$result = $mysqli->query($qry);
$count = $result->num_rows;
if( $count > 0)
echo " found user ";
else
echo " did not find user or password";
$mysqli->close();
?>

how to make with print_r only display text in array

I created a members table on my database and entered the username row as user and the password row as password. Then I wrote a script that has to display the password and the username in a database. This is it:
<?PHP
$user_name = "root";
$password = "Hunter123";
$database = "adventure_of_dragons";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM members";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
$id = array($db_field['member_id']); "<BR>";
$username = array($db_field['username']); "<BR>";
$password = array($db_field['password']); "<BR>";
$rank = array($db_field['rank']); "<BR>";
print_r($username);
print_r($password);
}
mysql_close($db_handle);
}
else {
print "Database NOT Found " . $db_handle;
}
?>
but when i run the code it displays this:
Array ( [0] => user ) Array ( [0] => password )
how do I make it display the text like this:
-User -Password
Please help.
That's simple. Just don't make arrays of them in the first place, and use regular echo.
Other bugs in the code
print_r is a debug function (just like var_dump), it is not used for printing out data to user.
Also, this statement: "<BR>"; simply means nothing.
You must echo it for it to have any effect at all.
Another thing is that you've overwritten the DB connection variables in your fetching loop. It's better to use constants for this, like shown below.
Here's your code, fixed
<?php
define("DB_USERNAME", "root");
define("DB_PASSWORD", "Hunter123");
define("DB_DATABASE", "adventure_of_dragons");
define("DB_SERVER", "127.0.0.1");
$db_handle = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$db_found = mysql_select_db(DB_DATABASE, $db_handle);
if ($db_found || true) {
$SQL = "SELECT * FROM members";
$result = mysql_query($SQL) or die(mysql_error());
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
// two <br>'s, so we get an empty line between users
}
mysql_close($db_handle);
} else {
echo "Database NOT Found " . $db_handle;
}

Fetching a result from selection query in php function

I have a php function of selection from mySql database:
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
echo $qry;
$result = mysql_query($qry);
while ($Res_user = mysql_fetch_assoc($result) ) {
return $Res_user['tax_id'];
}
}
an error is shown Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 446 and the line is while ($Res_user = mysql_fetch_assoc($result)
So what is the problem ? How can i fix it?
Try this
function Master_file($name, $latin ){
$dsn = 'mysql:host=localhost;dbname=nom';
$username = 'utilisaeur';
$password = 'K3Pud1';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$result = $db->prepare("SELECT tax_id FROM master where name =:name");
$result->bindValue(':name', $name);
$result->execute();
foreach($result->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $Res_user['tax_id'] . '<br />';
}
}
EDIT
The function above has just been updated to use PDO, display any errors, and output the tax_id value to the browser
You may try this, since your returning here return $Res_user['tax_id']; so I think you need a single row instead
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
if (!$connect) {
die("Could not connect: " . mysql_error());
}
$db=mysql_select_db($NAME_DB, $connect);
if (!$db) {
die ("Can't use " . $NAME_DB . " : " . mysql_error());
}
$qry = "SELECT tax_id FROM master where name ='" . $name . "' and latin = '" . $latin . "'";
$result = mysql_query($qry);
if( $result ){
$row = mysql_fetch_assoc($result);
return $row['tax_id'];
}
}

Categories