Can't get simple Object oriented row count to display - php

Been struggling with this for two days (and the rest). Read a couple of dozen posts from this site, been reading lots from w3 schools and lots of other resources online.
All I'm trying to do is show how many people have signed a petition.
After many failures, I wiped what I had and started from scratch.
I tried a few bits of code from w3 to check my connection to my database. The PDO didn't work at all, but object oriented worked fine. (Showed "connection successful" on my page.)
So then tried the code below, which I took from the PHP manual and still can't get it to work.
Would really appreciate some help.
<?php
$link = mysqli_connect("localhost", "my user", "my password", "my db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = mysqli_query($link, "SELECT Code, Name FROM 'wp_rm_submissions' ORDER BY Name")) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
printf("So far %d people have signed the petition.\n", $row_cnt);
/* close result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
I've also tried it without the single quotes around the table name.
My website is here.
It's a WordPress site, if that matters.

If you only need to count the records use select count:
SELECT count(Code) as count FROM wp_rm_submissions
This query will return a resultset with one record, the record will have a field called count and it's value will be the number of records stored in the wp_rm_submissions table.
A very very very simple example in php, using mysqli, would be:
<?php
// connect to mysql
$mysqli = new mysqli('host','user','password','schema');
// execute the query
$result = $mysqli->query('SELECT count(Code) as count FROM wp_rm_submissions');
// fetch the record as an associative array
$record = $result->fetch_assoc();
// get the value
$count = (int)$record['count'];
$mysqli->close();
printf("So far %d people have signed the petition.\n", $count);

Related

How to select a column for a MySQL table and compare it with a PHP variable

I am trying to compare a MySQL table column which I have imported to my script and compare it with a PHP value which I have defined.
I am trying to make an if loop that checks if any of the values in the column are equal to the variable.
// Connect to database containing order information
$servername = "server";
$username = "user";
$password = "pass";
// Create connection
$conn = new mysqli($servername,$username,$password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// define variables and set to empty values
$name = $ordernumber = "";
// Load up data from the form
$ordernumber = ($_POST['order_number']);
// Get SQL info
$sql = "SELECT order_number FROM p_orders;";
if ($conn->query($sql) === TRUE)
{
echo "Checked Orders.....";
}
else
{
echo "Failed to check orders, please contact Support for assistance" . $conn->error;
}
// Checking Script
if ($ordernumber === $orders)
{
echo "Order Number Found.... Let's Select a Seat";
}
else
{
echo "Your Order was not found, either you did not order a reservation ticket, have not waited 3 days or you entered the number wrong. If issues persist then please contact Support."
};
The end part of the script should be like this...
$stmt = $mysqli->stmt_init();
if ($stmt->prepare('SELECT order_number FROM p_orders WHERE orderID = ?')) {
$stmt->bind_param('s',$_POST['order_number']); // i if order number is int
$stmt->execute();
$stmt->bind_result($order_number);
$stmt->fetch();
if (!empty($order_number))
echo "Order Number Found.... Let's Select a Seat";
}else {
echo "Your Order was not found...";
}
$stmt->close();
}
$mysqli->close();
...note that the query now looks for only the records that match and note the use of prepared statement to make safe the post variable from SQL Injection.
The reason to collect only the matching items from SQL is otherwise, if you have a million records, the database would return all of them and then PHP will need to loop through them (this can cause maximum execution, memory and other errors). Instead databases where built to look things up like this - note an index on this field would be good and also use of a "youtube style" id is recommended, which is why I've assumed the use of a string for it's instead of a number as the variable minght imply - and it's not the "id" which is good for a number of reasons... I've added a link to explain "youtube style" id which I'll not go into detail here but there is a lot of win in using that :)
UPDATED based on...
http://php.net/manual/en/mysqli-stmt.prepare.php
MySQL prepared statement vs normal query. Gains & Losses
https://www.youtube.com/watch?v=gocwRvLhDf8 (Will YouTube Ever Run Out Of Video IDs?)
Preferably use a WHERE clause searching for the order id and mysqli prepared statement, like below.
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$name = "";
// Load up data from the form
$ordernumber = $_POST['order_number'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM p_orders WHERE orderID=?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $ordernumber ); // "i" if order number is integer, "s" if string
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($counter);
/* fetch value */
$stmt->fetch();
if ($counter>0) { // if order id is in array or id's
echo "Order Number Found.... Let's Select a Seat";
} else {
echo "Your Order was not found, either you did not order a reservation ticket, have not waited 3 days or you entered the number wrong. If issues persist then please contact Support."
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();

Displaying results in a search table (PHP)

This has probably been asked before, please feel free to link me or whatever, I just couldn't find exactly what I'm after.
It's pretty simple, I need to display the results of a search form. That part is easy and I can get that to work. What I'm having trouble with is when no results match what the user searched.
I'm fairly certain I need to just use an IF statement but I'm not very experienced with PHP and cannot figure out how to correctly display the code.
This is what I have so far:
$query = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
if (!$query)
{
echo "No results found in the database. Please go back and search again.";
}
My question is: How do I get the 'No results found...' message to display when the users search doesn't match anything in the database?
NOTE - I get very confused very quickly when it comes to trying to understand certain terms within PHP and SQL so please try to explain your answer like you would to an absolute beginner.
Many thanks in advance.
You want to show the "No results found"-message when no rows are found in the database table.
To do this, you can use below PHP and SQL code:
$sql = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
} else {
echo "No results found in the database. Please go back and search again.";
}
Note that the above answer is vulnerable to SQL injection attacks.
To prevent SQL injection attacks, it is recommended that you prepare and bind all user-submitted data, here is a better example that shows how SQL injection attacks can be prevented: (full example, including database connection)
$db = new PDO($dsn);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db->prepare("SELECT * FROM search WHERE isbn=:isbn OR bookname=:bookname OR author=:author OR category=:category");
$query->execute([ ':isbn'=>$isbn, ':bookname'=>$bookname, ':author'=>$author, ':category'=>$category ]);
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
} else {
echo "No results found in the database. Please go back and search again.";
}
Assuming you are using Mysqli ,
//connect with mysql
$conn = mysqli_connect("localhost", "user", "password", "db");
//here is the query
if($result = mysqli_query($conn,"SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'")){
if(mysqli_num_rows($result) > 0){
//mysqli_num_rows() returns the number of rows in a result .
//when it is greater than zero, it has some results
}
else{
echo "No results found in the database. Please go back and search again.";
//Do something if no results returned
}
}
//finally free the results
mysqli_free_result($result);
mysqli_close($conn);

php long polling using mysql

I found a script that uses php long polling.
It uses the following code to see if the text file is changed and returns the content.
This is received by the browser.
How can i change this to read a table and see if there are new events ?
$filename= dirname(__FILE__)."/data.txt";
$lastmodif = isset( $_GET['timestamp'])? $_GET['timestamp']: 0 ;
$currentmodif=filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif =filemtime($filename);
}
$response = array();
$response['msg'] =Date("h:i:s")." ".file_get_contents($filename);
$response['timestamp']= $currentmodif;
echo json_encode($response);
I have a table where there are 'posts'. post_id,content,user_id,posted_time
How can i know if theres a new post ?
You basically just have to fetch a new result, thats it, if you want to check if there are new results since the last execution of the script you have to save the output somewhere (is that what you want to do?)
See the following code, for a regular MySQL query:
<?php
// Connect to your MySQL DB
#$db = mysqli_connect("localhost", "root", "", "database");
// Check connection and echo if an error occurs
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
// Execute SQL Query, replace this with your Query (maybe the one I put in fits for your needs)
$query = mysqli_query($db, "SELECT * FROM posts");
// Transform the result into an array if your you got new elements in the MySQL DB.
$resultat = mysqli_fetch_assoc($befehl);
// Close connection
mysqli_close($db);
?>

mysqli migration issue and security advices

I tried to migrate from mysql to mysqli but this code doesn't work. I'm new to php and mysql
$link = mysqli_connect("localhost", "user", "password", "db");
/* check connection */
if (mysqli_connect_errno()) { printf("Connect failed: %s\n",
mysqli_connect_error()); exit(); }
if ($result = mysqli_query($link, "SELECT * FROM users WHERE uid='$uid'")) {
if(mysqli_num_rows($result) != 0) {
mysqli_query($link, "UPDATE users SET array='$array' WHERE uid='$uid'");
}
else {mysqli_query($link, "INSERT INTO users (uid,array) VALUES ('$uid','$array')"); }
mysqli_free_result($result); }
/* close connection */
mysqli_close($link);
?>
So my questions are:
what should be changed to make this code work;
what security vulnerabilities does this code have and what changes in the code would you suggest to fix that?
Thanks for spending time to answer my questions.
You need to set error reporting to maximum level and make error messages available. this way you will let PHP to tell you what is going wrong and what needs to be fixed.
however, sometimes our code still doesn't work yet there are no error messages around. it's time to do some debugging
You have to change this code to make every variable to go into query via placeholder only
however, raw mysqli is extremely bad with prepared statements, so, I would recommend not to use it but rather move toward PDO or safeMysql. A latter one will let you to have safe queries with the same amount of code.
if ($db->getOne("SELECT 1 FROM users WHERE uid=?i",$uid))
{
$db->query("UPDATE users SET array=?s WHERE uid=?i",$array,$uid);
} else {
$db->query("INSERT INTO users (uid,array) VALUES (?i,?s)",$uid,$array);
}
By the way, Mysql lets you to make all these three queries in one:
$sql = "INSERT INTO users (uid, array) VALUES (?i,?s)
ON DUPLICATE KEY UPDATE array=values(array)";
$db->query($sql, $uid, $array);

Basic MySQL help? - submitting data

I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code
<IMG>
I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
$mysqli = mysqli_init();
//Log in to the DB
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)
If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)
Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;
and then fetch the query results.
If this does not answer your questions please provide some clarifications.
Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
$conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
?>
Read more here.

Categories