PHP syntax wrong? Outputting Resource id #3 - php

<?php
$link = mysql_connect('localhost', 'user', 'password');
if (!$link) {
die('Failed to connect to MySQL: ' . mysql_error());
}
$db_selected = mysql_select_db('mysql', $link);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
$query = sprintf("SELECT church_id FROM hours
WHERE day_of_week = DATE_FORMAT(NOW(), '%w') AND
CURTIME() BETWEEN open_time AND close_time",
mysql_real_escape_string($day_of_week),
mysql_real_escape_string($open_time),
mysql_real_escape_string($close_time));
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' .mysql_error() . "\n";
$message .= 'Whole query: ' .$query;
die($message);
}
while ($row = mysql_fetch_array($result)) {
echo $row['shop_id'];
}
mysql_free_result($result);
echo "end";
?>
I know SQL query works by copying/pasting into phpmyadmin. I want the script to just output a shop_id or series of shop_ids. Right now it outputs Resource id #3. I looked up how to fix it and mysql_fetch_array was supposed to be the answer. What am I doing wrong?

I'm looking over your query and I only see you selecting church_id and you want to output shop_id, you should include that in your select like so:
$query = sprintf("SELECT church_id, shop_id FROM hours WHERE day_of_week = DATE_FORMAT(NOW(), '%w') AND CURTIME() BETWEEN open_time AND close_time",
mysql_real_escape_string($day_of_week),
mysql_real_escape_string($open_time),
mysql_real_escape_string($close_time));
$result = mysql_query($query);

You have several problems here, the first of which is that you are using the mysql extension which is unmaintained and officially deprecated (due to be removed). I suggest you try mysqli...
$link = new mysqli('localhost', 'user', 'password', 'mysql');
if ($link->errno) {
throw new Exception($link->error, $link->errno);
}
Whilst you've done a commendable job of securing your query, you really should be using the better tools available in mysqli, notably prepared statements...
$stmt = $link->prepare('SELECT church_id FROM hours
WHERE day_of_week = DATE_FORMAT(NOW(), ?) AND
CURTIME() BETWEEN open_time AND close_time');
if (!$stmt) {
throw new Exception($link->error, $link->errno);
}
$stmt->bindParam('s', $day_of_week); // assuming $day_of_week is properly defined
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
Fetching data from a mysqli prepared statement is a little different to the old mysql_fetch_array however it's not difficult. One way is to use result binding
$stmt->bind_result($church_id);
while ($stmt->fetch()) {
echo $church_id;
}

Related

PHP Multiple Prepared Statements

I would like to execute two statements and print the results within a while loop. Each statement will select data from two different tables.
I'm not sure the best way to approach this.
My code so far is as follows;
$conn = new mysqli('localhost', 'user', 'password', 'db');
if ($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$curDate = date("Y-m-d");
//first stmt
$stmt = $conn->prepare("SELECT start, status FROM log WHERE start >= ?");
$stmt->bind_param('s', $curDate);
$stmt->execute();
$stmt->bind_result($start, $status);
$stmt->close();
//second stmt
$stmt = $conn->prepare("SELECT time FROM params");
$stmt->bind_result($time);
$stmt->execute();
$stmt->close();
/* fetch values and echo for testing */
while ($stmt->fetch()) {
echo $start;
echo $status;
echo $time;
}
Any help is appreciated.
In general, there is nothing special in running two or dozen prepared statements - you just have run them one by one. Thus there is no "best way" at all.
In your particular case the best way is to get rid of prepared statements:
$time = $conn->query("SELECT time FROM params")->fetch_object()->time;
$res = $conn->query("SELECT start, status FROM log WHERE start >= CURDATE()");
while($row = $res->fetch_object())
{
echo $row->start;
echo $row->status;
echo $time;
}

Get a row from a database based on querystring

BIt of a php/mysql noob here, hope someone can help.
Ok so i have a URL which has an id in the querystring like so: wwww.mysite.com/page1.php?id=1
What i want to do is connect to a table in the database and get the data from the columns on one row where the first column named ID equals the id number held in the querystring.
I then want to print the data from each column in different div's elsewhere on the page.
There's also the additional issue of what to do if there's no row in the table with the same id as the querystring, i'd want it to change the id in the querystring to 1 and load that rows data.
I had a little go, i know it connects ok but i have no idea if the rest is what i want:
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=".$_GET['ID']."";
echo $result['A'];
mysql_close($link);
?>
And then put this in the div's to print the data.
<?php echo $result['A']; ?>
Am i along the right lines or completely wrong?
$dbConnection = mysql_connect('Address', 'Database', 'Password');
if (!$dbConnection) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = $dbConnection->prepare("select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per = ?");
$query->bind_param('s', $per);
$query->execute();
$result = $query->get_result();
<?php echo $result; ?>
use this code first to avoid SQL Injection second that's the way it should work in PHP first prepare the query second execute and only then show it.
Use mysql_query function in your code.
mysql_* functions is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=$per";
$result = mysql_query($query, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['A'];
mysql_close($link);
?>

How to convert mysql to mysqli? [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I tired to convert my mysql to mysqli but seems to be getting a lot of errors and warnings i got no problem connecting to the data base but the rest of the code seems wrong what am i doing wrong?
sql:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("searchengine");
$sql = mysql_query(sprintf(
"SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
'%'. mysql_real_escape_string($_GET['term']) .'%',
$_GET['results']));
while($ser = mysql_fetch_array($sql)) {
echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
}
// don't forget to close connection
mysql_close();
?>
mysqli
<?php
mysqli_connect("localhost","root","","searchengine") or die("Error " . mysqli_error($link));
$result = mysqli_query(sprintf(
"SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
'%'. mysqli_real_escape_string($_GET['term']) .'%',
$_GET['results']));
while($ser = mysqli_fetch_array($result)) {
echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
}
mysqli_close();
?>
you can try it by creating a mysqli object like described here: http://www.php.net/manual/en/class.mysqli.php
or simply like this:
$db = new mysqli($hostname, $username, $password, $database);
and then query it like this:
$result = $db->query('SQL HERE');
in your case the code for mysqli would look like this
$db = new mysqli("localhost","root","","searchengine");
$result = $db->query(sprintf(
"SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
'%'. mysqli_real_escape_string($_GET['term']) .'%',
$_GET['results'])
);
while($ser = mysqli_fetch_array($result)) {
echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
}
Try using OOP style instead of procedural, it is much cleaner and more readable:
$mysqli = new mysqli("localhost", "root", "", "searchengine");
$result = mysqli->query(sprintf(
"SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
'%'. mysqli_real_escape_string($_GET['term']) .'%',
$_GET['results']));
May I also suggest you read some articles about how to use mysqli and preparted statements, instead of just hacking away and not reading the documentation. Using prepared statements removes the need for sprintf. Here are some useful links:
PHP Website - http://www.php.net/manual/en/book.mysqli.php
An article I found on google in about 5 seconds and looks quite good -http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/
In mysql, we used mysql_real_escape_string because you couldn't prepare statement.
Now with mysqli, you have the ability to prepare statements which is the preferred way.
<?php
$mysqli = new mysqli("localhost", "root", "password", "searchengine");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
}
$query = "SELECT * FROM searchengine WHERE pagecontent LIKE ? LIMIT 0,?";
$stmt = $mysqli->prepare($query);
if (!$stmt) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$term = '%'.$_GET['term'].'%';
$result = $_GET['results'];
$stmt->bind_param("si", $term, $result);
$stmt->execute();
while ($ser = $stmt->fetch_assoc()) {
echo "<h2><a href='".$ser['pageurl']."'>".$ser['pageurl']."</a></h2>";
}
$mysqli->close();
?>

Moving from MySQL to MySQLi

Could somebody please point me in the right direction. I am in the process of making the transition from MySql to MySqli. Normally I would select from the database using th code below and it would allow me to easily use the column value as a working variable:
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = mysql_query($SQLCommand);
$DataRow = mysql_fetch_assoc($Data);
$var1 = $DataRow["column1"];
$var2 = $DataRow["column2"];
$var3 = $DataRow["column3"];
$var4 = $DataRow["column4"];
I have researched how to do the MySql equivalent but I find theres a lot of different way using loops etc. Is there a like for like (for want of a better description) that does the same thing? Thanks in advance.
Instead of going with the flow, i care to suggest a PDO alternative
$db = new PDO($dsn, 'username','password');
//$dsn is the connection string to your database.
//See documentation for examples
//The next two rows are optional, but i personally suggest them to
//ease developing, debugging (the 1st) and fetching results (the 2nd)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$stmt = $db->prepare("SELECT * FROM table WHERE column1 = :c1");
$stmt->bindValue(':c1', 'ok'); //This example is trivial and not necessary
//but it gains relevance when the bound value
//is a variable
$rows = $stmt->fetchAll(); //if you expect a single row use fetch() instead
//do something with the results
You can read more about PDO here: PDO manual
The biggest PDO advantage is that it's independent of the actual database in use by your application. If, by chance, you want to change database in the future, for example SQLITE or PostgreSQL, the only* change you have to make is your $dsn connection string
[*] True only if you used standard SQL queries and nothing vendor-specific.
A direct conversion would be:
$Data = mysqli_query($connection, $SQLCommand);
$DataRow = mysqli_fetch_assoc($Data);
The difference, other than the i is that mysqli_query requires the connection as an argument (as do most mysqli_* functions).
MySQLi also has an object oriented style:
$Data = $connection->query($SQLCommand); // assuming you created the $connection object
$DataRow = $data->fetch_assoc();
They should be like
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = $mysqli->query($SQLCommand);
$DataRow = $mysqli->fetch_assoc($Data);
Try this LINK
My suggestion is to use mysqli prepared statement whenever you are using user inputs to prevent SQL injection:
See below code uses object oriented approach and prepared statement
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
!$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
!$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = ?");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
//note below "i" is for integer, "s" can be used for string
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

mysql_query does not return a resource

I've been all up and down StackExchange, and much of the internet's cornucopia of lesser sites, looking for any good reason my code doesn't work, but this one has me stumped. I'd like to display the total number of rows in a particular MySQL table, and set the count as a variable, to use later in the script. When I run the following, the script dies, and I get a PHP warning, telling me that mysql_result() expects parameter 1 to be resource, string given.
$conn = mysql_connect('mysql_server', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
mysql_select_db('my_database', $conn);
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
$max_count_query = ("SELECT COUNT(*) FROM table");
// Perform Query
$max_count_action = mysql_query($max_count_query);
$mcount = mysql_result($max_count_action, 0, 0);
printf("\nNumber of Records to Process: ", $mcount);
What does the collective genius of StackOverflow think?
In response to the comments, I have another mini-slab of code to offer:
$conn = mysql_connect('127.0.0.1', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
mysql_select_db('my_database', $conn);
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
$max_count_query = ("SELECT COUNT(*) FROM directory_nap");
// Perform Query
$max_count_action = mysql_query($max_count_query);
if (!$max_count_action){
die('mysql query error: ' . mysql_error());
}
$mcount = mysql_result($max_count_action, 0, 0);
if (!$mcount){
die('mysql result error: ' . mysql_error());
}
printf("\nNumber of Records to Process: ", $mcount);
Provided the table tablename is just a sample (see answer by bitfox), there's nothing wrong with your code. I can use the same code on my test server and get results by changing the table name to one that I know exists in my own db.
What is most troubling, however, is that you indicate the error says mysql_result() expects parameter 1 to be resource, string given -- if your SQL has an error, mysql_query returns boolean (docs), not a string. So, you're either not showing the same test code as you're actually using, or you've given us an inaccurate error message.
At some point, you must be assigning a string into the variable $max_count_action. Here's what I get when I send a query with an intentional problem: Warning: mysql_result() expects parameter 1 to be resource, boolean given -- note "boolean", not string.
So, I think your first step is to choose a different table name. That said, if you're using a reserved word as a table or column name you can still access it by surrounding the string in the backtick (`) character:
SELECT COUNT(*) FROM `table`
Second step is to see what's happening to $max_count_action to turn it into a string. Finally, use mysql_error consistently to debug, I would suggest doing something a little nicer with it than die for production code, however.
// working code on my test server
$max_count_query = ("SELECT COUNT(*) FROM users");
$max_count_action = mysql_query($max_count_query);
$mcount = $max_count_action ? mysql_result($max_count_action, 0) : 'Error: '.mysql_error();
print "\nNumber of Records to Process: ". $mcount;
it's very likely that the error is here:
SELECT COUNT(*) FROM table
"table" is a reserved word of SQL language. You should change it.
The cause of the problem is not clear from the code sample (it could be a wrong table name, the parentheses around the query string, and so on), however there are a number of inaccuracies in it. You can try the following code, it should at least fix a couple side bugs and give you more details on the error:
$conn = mysql_connect('mysql_server', 'username', 'password');
if ($conn === false) {
die('Connect Error ' . mysql_error($conn));
}
if (mysql_select_db('my_database', $conn) === false) {
die('Could not select database: ' . mysql_error($conn));
}
$max_count_query = "SELECT COUNT(*) FROM table";
// Perform Query
$max_count_action = mysql_query($max_count_query, $conn);
if($max_count_action === false) {
die('Query error ' . mysql_error($conn));
}
$mcount = mysql_result($max_count_action, 0, 0);
if($mcount === false) {
die('Result retrieval error ' . mysql_error($conn));
}
printf("\nNumber of Records to Process: %s", $mcount);
mysql_free_result($max_count_action);
Hope this helps, bye!
Is the 'table' in your question a placeholder or a real name in your code? Try to change another name of your 'table' table, otherwise I would like to try mysql_fetch_array instead of mysql_result
$max_count_query = "SELECT COUNT(*) FROM t";
// Perform Query
$max_count_action = mysql_query($max_count_query) or die (mysql_error());
$mcount = mysql_fetch_array($max_count_action);
printf("\nNumber of Records to Process: ", $mcount[0]);
$conn = mysql_connect('mysql_server', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
This is OK, but the connect and coditional don't need to be split across 2 lines
mysql_select_db('my_database', $conn);
Again, this is questionable. If you're using multiple databases then referencing databases in your SQL is much simpler and safer than tracking state within your PHP code.
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
Haven't you already done that?
$max_count_query = ("SELECT COUNT(*) FROM table");
Why the brackets?
// Perform Query
Isn't that obvious from the code?
$max_count_action = mysql_query($max_count_query);
$mcount = mysql_result($max_count_action, 0, 0);
It would be neater to pass the db handle to the mysql_query call.
You checked for an error after connecting, you checked for an error after switching database, but you don't check for an error after mysql_query() ?
printf("\nNumber of Records to Process: ", $mcount);
There is no placeholder in the format string for the mcount argument.Try:
printf("\nNumber of Records to Process: %d", $mcount);
I get a PHP warning, telling me that mysql_result() expects parameter 1 to be resource, string given.
Then the code you are running is not the code you've shown us; mysql_query() will not return a string.

Categories