Warning: mysql_select_db() expects parameter 2 to be resource, - mysql

<?php
$servername = "localhost";
$username = "root";
$password = "Rachel";
$db = "hairdressingapointments";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected Sussessfully";
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
$sql = "SELECT `ApointmentDate`, `ApointmentTime` FROM `apointments` WHERE `staff_id`=1 && `quantity`>0";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo $sql;
mysql_close();
?>
spent hours trying to figure this out and im guessing its something so simple. getting back the following error:
Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\wamp2\www\hairdressingapointments\TeresaApointments.php on line 15 which is,
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());

You already connected to the database using
mysqli_connect(...);
So, you do not need
mysql_select_db(....);
Also change the query to this
$sql = "SELECT ApointmentDate, ApointmentTime FROM apointments WHERE staff_id=1 AND quantity>0";
If you use SQLWorkbench or SQLYog or some other tool, you can enter your SQL and make sure it is valid before adding it to your script.
Also, make sure the table name is really
apointments
and not
appointments
I got this information from php.net - mysqli_connect

Related

I have an SQL syntax error when inputing data

I'm a beginner programmer and I'm getting a problem that I cannot seem to overcome. I predict it's a small syntax error but I don't know.
The code I'm using is the following:
<?php
$x=$_POST['firstname'];
$y=$_POST['lastname'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname="db1";
//Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT INTO 'user' ('fname', 'lname') VALUES ('$x','$y')";
if ($conn->query($sql) === TRUE) {
echo "New record created succesfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Once I press submit to input the data the following error comes up:
Connected successfullyError: INSERT INTO 'user' ('fname', 'lname') VALUES ('rty','rty')
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''user' ('fname', 'lname') VALUES ('rty','rty')' at line 1
Any help? Thanks in advance.
update your query replace single quote(') from table name and column name with (`), Like
$sql = "INSERT INTO `user` (`fname`, `lname`) VALUES ('$x','$y')";

How to make reference to one of my MySQL databases inside my PHP file?

I have already asked this related question: https://webmasters.stackexchange.com/questions/116055/using-mysql-database-data-directly-into-generating-articles-for-my-website-new/116056?noredirect=1#comment154341_116056
At this point, I'm starting to understand the code syntax and project structure a little better.
But I have made my database using MySQL console. it only has a few entries so far, I wanted to try to adapt the code in Zach's example, but here is the problem I have:
The problem is, I am unsure how to get the reference to my database object? In the code sample from Zach there is variable $db, I guess this is where i need to keep a reference to my own actual database.
Here is the psuedo-code (maybe) from Zach, note: he always said to me not to copy-paste it, but I'm just trying to see how I can use it in my project.
<?php
$SQL_Query = "SELECT * FROM your_table";
$SQL_Run = mysqli_query($db, $SQL_Query);
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
?>
So my question simply at moment is: How to create the reference $db?
Your answer is the correct way to establish a connection. I want to point out that there are two ways of writing that statement. The version you found online is one way, but from our previous conversation, you can write it like this:
<?php
// Establish how to log in
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// create the database connection
$db = new mysqli($servername, $username, $password, $dbname);
// if it fails, kill the site.
if (mysqli_connect_error($db)) {
die("Connection failed: " . mysqli_connect_error($db));
}
// your first query to grab all the article data
$SQL_Query = "SELECT * FROM your_table";
// run the query
$SQL_Run = mysqli_query($db, $SQL_Query);
// while data exists (it makes sure that you have post data, otherwise nothing shows up)
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
// Close the connection
mysqli_close($db);
?>
You will notice that the connections are written like a function.
mysqli_num_rows($result);
instead of
$result->num_rows
Both do the same thing, just a personal preference. That should hopefully clear some things up from your first post :)
I have got further on and I think have answered my own question. I found it a bit tricky to research because I don't understand all the different terms and names of features/api/scripts/etc. But I had just to read the documentation for mysqli_connect(), I set up the code as follows and now I have pulled all the data from the database into words on my html/php files.
From here I think I can rewrite the code to first sort it by date and then can of course put the latest posts at the top of each page etc.
I can also allow the user to click 'Genre' and only view Comedy for example.
Here is the code just to get the data parsed into my index.php file:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, title FROM releases";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Type: " . $row["type"]. " - Title " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I extended upon the above work by making the php script fetch all the entries in the database and create the previous html article I had once for each entry. In the SELECT statement I can control which types of entries are displayed (eg. For a certain category). Here was how I did it:
// make an html article based snippet (image, title, description, etc),
//once for each entry in the database table...
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepassword";
$dbname = "somedatabasename";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM releases ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<section class="wrapper style1">';
echo '<div class="inner">';
echo '<header class="align-center">';
echo '<h2>'. $row["title"] . '</h2>';
echo '<div class="image fit">';
echo '<img src='. $row["imgurl"] .'>';
echo '</div> <p> RELEASE TITLE: ' . $row["title"] . '<br /> DATE POSTED: ' . $row["postdate"] . '<br /> DESCRIPTION: ' . $row["description"] . '</p>';
echo 'DOWNLOAD LINK: '.$row["link"].' <br />';
$NfoLink = $row["nfolink"];
if ($NfoLink != 'not found' && $NfoLink != '')
{
echo 'NFO LINK/MORE DOWNLOADS: '.$row["nfolink"].'';
}
echo '</header>';
echo '</div>';
echo '</section>';
}
}
else
{
echo "0 results";
}
$conn->close();
?>

I got empty result with MySQL

I have tried to show the whole table data in MySQL. Rows are (User_id, first_name, last_name, and dept). There is no result when I refresh the page.
<?php
$servername = "fdb19.awardspace.net";
$username = "2598428_db";
$password = "password";
$dbname = "2598428_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT * From users";
$result = $conn->query($sql);
while($res = mysqli_fetch_array( $result )) {
echo $res['AverageSatisfactionScore'];
}
?>
Your echo is false.
You need to display a valid column name like :
echo $res['id'] or echo $res['dept'].
just try to print the total count of your result set by
echo mysqli_num_rows( $result );
it will print total number of records in the result
Also try to print whole row by
print_r($res);
insted of using
echo $res['AverageSatisfactionScore'];

Getting 2 Notice: Undefined Variable errors

The two errors are as below:
Notice: Undefined variable: HawA_Homes in C:\wamp\www\HawA_CIS241\InsertRecord.php on line 48
Notice: Undefined variable: HawA_Homes in C:\wamp\www\HawA_CIS241\InsertRecord.php on line 56
I've checked my names and they appear correct and I am not sure how to proceed now.
Code is as below:
<?php
$hostName = "localhost";
$databaseName = "test";
$userName = "root";
$password = "";
$tableName = "HawA_Homes";
//try to connect report error if cannot
$db = new mysqli($hostName, $userName, $password, $databaseName) or die(" Could not connect:" . mysql_error());
print(" Connection successful to host $hostName <br /> <br />"); //report connection success
//Get data to create a new record
$Address = $_REQUEST["address"];
$DateBuilt = $_REQUEST["dateBuilt"];
$Value = $_REQUEST["value"];
$Size = $_REQUEST["size"];
$Number_of_floors = $_REQUEST["floors"];
$sql = "INSERT INTO $HawA_Homes('Address','DateBuilt','Value','Size','Number_of_floors')VALUES{'$Address','$DateBuilt','$Value','$Size','$Number_of_floors')"; //Create insert query for new record
//try to query dataase / store returned results and report error if not successful
if(!$result =$db->query($sql))
{
//die('There was an error running the query[' .$db->error . ']';
}
print("SQL query $sql successful to database: $HawA_Homes <br /><br />"); //report sql query successful.
?>
You have these notices because the variable $HawA_Homes isn't declared in your code before being used at line 48 and 56. (These are just notices, they are not critical errors, you can avoid displaying them by adding error_reporting(E_ALL & ~E_NOTICE); at the begining of your code, like explained here)
In fact, you used $HawA_Homes instead of $tableName in these lines. Replace them, you won't have notices anymore for these lines.

Xcode connect error

I have Xcode 4.6.
I want connect mysql database with my app.
So i found this tutorial
http://www.youtube.com/watch?v=ipppykYUzh4#at=104,http://www.youtube.com/watch?v=tvv1KlZ-594
I am was continue Step by Step but i do not know where is my error.
this is my xcode project. Plese look at this and tell me what is wrong.
https://www.dropbox.com/s/4pj1xj4f736l42m/mysql.zip
Thanks for help.
this is php code
<?php
header('Content-type: application/json');
$DB_HostName = '127.0.0.1';
$DB_Name = 'test';
$DB_User = 'root';
$DB_Pass = '';
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = 'SELECT * FROM phpmysql';
$result = mysql_query($sql,$con) or die(mysql_error());
$num = mysql_numrows($result);
mysql_close();
$rows =array();
while ($r = mysql_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
?>
THIS IS MY ERROR
2013-07-30 10:27:22.335 mysql[4095:c07] *** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2380.17/UITableView.m:4460
2013-07-30 10:27:22.336 mysql[4095:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
*** First throw call stack:
(0x1c91012 0x10cee7e 0x1c90e78 0xb64665 0xc46c4 0x2c88 0xcd8fb 0xcd9cf 0xb61bb 0xc6b4b 0x632dd 0x10e26b0 0x228dfc0 0x228233c 0x228deaf 0x1022bd 0x4ab56 0x4966f 0x49589 0x487e4 0x4861e 0x493d9 0x4c2d2 0xf699c 0x43574 0x4376f 0x43905 0x4c917 0x1096c 0x1194b 0x22cb5 0x23beb 0x15698 0x1becdf9 0x1becad0 0x1c06bf5 0x1c06962 0x1c37bb6 0x1c36f44 0x1c36e1b 0x1117a 0x12ffc 0x243d 0x2365)
libc++abi.dylib: terminate called throwing an exception
(lldb)
Ok, the problem here is that your PHP script returns json_encode($rows) at first, then a var_dump($rows). So, clearly, it's not a JSON that is returned, while your Objective-C code expects a JSON.
Try adding a header('Content-type: application/json'); in the beginning of your file, and remove the var_dump at the end.
EDIT : this is the new PHP script
<?php
header('Content-type: application/json'); // Specify that the result of your script is a JSON
$DB_HostName = '127.0.0.1';
$DB_Name = 'test';
$DB_User = 'root';
$DB_Pass = '';
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = 'SELECT * FROM phpmysql';
$result = mysql_query($sql,$con) or die(mysql_error());
$num = mysql_numrows($result);
mysql_close();
$rows =array();
while ($r = mysql_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
?>
EDIT 2 : Here is a similar question to yours, see the answer.