Can not execute the MySQL query using PHP and MySQL - php

I have an issue when executing the sql query.I am explaining my code below.
complain.php:
require_once("./include/dbconfig.php");
if($_REQUEST['typeOfApp']=="WEB"){
$sent_form="Web";
$ticket_id=generateTicketId('W1');
}
function generateTicketId($code){
$sql="select * from db_ticket order by id desc ";
$qrylast=mysqli_query($con,$sql);
echo mysqli_num_rows($qrylast);exit;
}
Here i am trying to check the number of rows.But I am not getting anything.I am giving my dbconfig.php below.
dbconfig.php
$con = new mysqli("localhost", "root", "****", "************");
if ($con->connect_error)die("Connection failed: ");
Here i need to check the no of rows present inside the table.Please help me.

You need to define your connection variable global so you have to access in inside your function OR you need to pass it in function parameter
require_once("./include/dbconfig.php");
//global $con;
if($_REQUEST['typeOfApp']=="WEB"){
$sent_form="Web";
$ticket_id=generateTicketId('W1',$con);// pass connection variable
}
Pass your $con variable as parameter and function need return value
function generateTicketId($code, $con) {
$sql = "select * from db_ticket order by id desc ";
$qrylast = mysqli_query($con, $sql);
$rows = mysqli_num_rows($qrylast);
if($rows>0){
return $rows;
}else{
return FALSE
}
}
http://php.net/manual/en/language.variables.scope.php

Related

Return inserted row ID in wordpress wpdb

I want insert some data to a table of the wordpress then return it's auto increase id value.
I do this but both of these has error:
INSERT INTO wp_sho_app_form (job_id, first_name, last_name) VALUES(1, 'Caldwell', 'Estrada');
SELECT LAST_INSERT_ID();
This code word well in MySql but by $wpdb I get this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'SELECT LAST_INSERT_ID()' at line 1
I call this statement by $wpdb->query and also $wpdb->get_results, but both of them has that error.
I don't want use $wpdb->insert for some reasons and I should use this type of code.
The correct way is to use insert_id.
$lastid = $wpdb->insert_id;
if your make another query its not consistent if you have new entries and a lot of traffic. That can cause wired problems.
And that is only working after insert and you should use them. Don't fight the framework.
You can run a custom query then another to select the last item in the table. If you are using a stand alone php file you need to include the wp-load.php file to get the wordpress functions.
$query = "
INSERT
INTO wp_sho_app_form
(job_id, first_name, last_name)
VALUES
(1, 'Caldwell', 'Estrada')
";
$wpdb->query($query);
$query = "
SELECT *
FROM wp_sho_app_form
ORDER BY col_id desc
LIMIT 1
";
$wpdb->query($query);
There is no way to do multiple query by wpdb. The solution which I could find lastly is using direclty MySqli. I wrote this two function for do it. May be it be useful for sombody. As in ajax wordpress not load so I check to find wp-config fle to get details of connection at first:
public static function run_query($query)
{
$wp_config_path = script_generator::get_wp_config_path();
if($wp_config_path == null){
echo 'Could not found wp_config file!';
return;
}
require_once $wp_config_path;
$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result_count = 0;
$result_set = array();
if ($mysqli->multi_query($query)) {
do {
$current_result_count = 0;
$current_result = array();
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
$current_result[$current_result_count] = $row;
$current_result_count++;
}
$result->close();
}
$result_set[$result_count] = $current_result;
if ($mysqli->more_results()) {
$result_count++;
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
return $result_set;
}
function get_wp_config_path(){
$dir = dirname(__FILE__);
do {
if( file_exists($dir."/wp-config.php") ) {
return $dir."/wp-config.php";
}
} while( $dir = realpath("$dir/..") );
return null;
}

Changing mysql_connect to mysqli causes function to fail

To begin with, I am a novice when it comes to PHP and MySQL.
I have a MySQL table called levels that contains two columns: level_id and mapData. Some time ago, I wrote a piece of code using mysql_connect that takes user inputted level_id and fetches the corresponding mapData from the table, and the code works as intended. See below:
<?php
$mysql_host = 'localhost';
$mysql_user = 'username';
$mysql_password = "password";
$mysql_database = 'database';
if (!mysql_connect($mysql_host,$mysql_user,$mysql_password)||!mysql_select_db($mysql_database)){
die('Connection failed');
}
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysql_query($query)){
if($query_result = mysql_result($query_run,0,$field)){
return $query_result;
}
}
}
$user_input = mysql_real_escape_string(base64_decode($_GET["level_id"]));
$sql = "SELECT level_id FROM levels WHERE level_id='$user_input'";
$result = mysql_query($sql);
if(mysql_num_rows($result) >0){
$mapData = get_map_data($user_input,'mapData');
print $mapData;
}else{
echo "0";
}
?>
In the case that the user inputs a level_id that does not exist in the database, instead of mapData, he will receive 0. Everything works! I, however, read that mysql_connect is deprecated as of PHP 5.5 and decided to switch from using it in my file to using mysqli:
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
After changing to mysqli, my get_map_data function has stopped working. I have made certain that the mysqli connection works, but I am simply hitting my head against the wall in making my function work using it. How do I fix my get_map_data function so that it functions again using mysqli?
You can't mix mysqli and mysql_ functions. Furthermore, your mysqli initialization is creating an object, not a resource. Lastly, there is no mysqli_result() function, so therefore we need to emulate what you're trying to do. You wanted the first row 0 and then wanted a specific $field. Below should be what you want.
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = $mysqli->query($query)){
//no mysqli->result() function, so we need to seek to the row.
$query_run->data_seek(0);
if($query_result = $query_run->fetch_assoc()){
return $query_result[$field];
}
}
}
your get_map_data function currently has query running using mysql_query you have to change that to mysqli_query in order to execute:
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysqli_query($conn,$query)){
if($query_result = mysqli_result($query_run,0,$field)){
return $query_result;
}
}
}

switch from mysql to mysqli Undefined variable: connect

I would like to switch from mysql_* to mysqli_* because I've read, that soon mysql_* won't be supported anymore.
Now I have a problem, that the functions which I wrote dont work anymore.
At the index.php file I have
global $connect;
$connect = mysqli_connect('localhost', "username", "password");
and at the functions.php file I have
function count_total_messages(){
$result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
$qry = mysqli_query($connect,$result);
return $qry['total'];
}
But I get the following error:
Undefined variable: connect
What should I do? Everywhere the mysqli_query works except those from the functions.php file.
function count_total_messages(){
global $connect; //You need a locally defined connect variable
$result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
$qry = mysqli_query($connect,$result);
return $qry['total'];
}
You are doing the global the wrong way around. In your index you just need
$connect = mysqli_connect('localhost', "username", "password");
And in your functions you use this:
function count_total_messages(){
global $connect;
$result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
$qry = mysqli_query($connect,$result);
return $qry['total'];
}

Php Custom Function For Mysql Query Not Working

I have created two functions one for connecting to MySQL database and one for running a specific query.
I enter the database name as parameter for first function to connect to the database, this works fine, but my problem is with the second one.
2nd function returns the $result from running a query, but when I use mysql_fetch_array with the $result, it gives one output even if it supposed to give more than one.
As I am no php expert so i can't find the solution. Please help me.
Here is the code:
File Function.php
<?php
function myconnect($data)
{
$db_host='localhost';
$db_user='root';
$db_pwd='';
$data=$data;
$dbc = mysqli_connect($db_host, $db_user,$db_pwd,$data) or die (mysql_error());
return $dbc;
}
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
$query="SELECT *FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC";
$result = mysqli_query($dbc, $query);
return $result;
}
?>
File test.php
<?php
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
//runquery('database','table','col','id')/
while($row=mysqli_fetch_array($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}
?>
If I am doing all wrong then suggest me a better way :-)
A quick glance shows that in your function runquery
SELECT *FROM
should be
SELECT * FROM
note the space after the *
EDIT :
I also notice you are using *mysqli_fetch_array* and this is not a valid mysqli method. You are right in using the mysqli extension over mysql but you should look more into statement fetch to solve this issue. The link I provided give a procedural example that should work for what you need.
function myconnect($db)
{
/*Removed redundant - single use variables*/
/*DB name was passed to the client_flags parameter of mysql_connect instead of mysql_select_db*/
$dbc = mysql_connect("localhost", "root","") or die (mysql_error());
/*Inserted Line*/
mysql_select_db($data);
return $dbc;
}
Currently you're not selecting a database - equivalent of USE DATABASE db_name.
Couple of syntax changes and function definition
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
/*Query and link identifier were in the wrong order*/
return mysql_query("SELECT * FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC", $doc);
}
Finally a couple of syntax changes, function calls
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
/*fetch associateive array of result during iteration*/
while($row=mysql_fetch_assoc($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}

Scope of PHP function [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 2 years ago.
I have a file that corrals my re-usable functions into one file (functions.php). It's include_once()'d on every page that needs it. I'm getting an error when my custom functions are trying to access a MySQL connection outside their own scope. The source is a bit like this:
<?php
// functions.php
$connect = mysql_connect("localhost", "user", "pass") or die("MySQL said: ".mysql_error());
mysql_select_db("database", $connect) or die("MySQL said: ".mysql_error()); // no error
/* ... */
function getmotd($user) {
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
?>
Why can't my function access variables declared above it's scope? I can get a successful connection by reproducing $connect's declaration within the function.
Any insight into how I can work around this or what I'm doing wrong here?
You can't access $connect because it is outside the scope of the function; that is, PHP can only see the variables within the function when it's inside it. You could use the global keyword to let PHP know the variable is outside the function's scope as Kemal suggests, but I think a better course of action is to pass the connection into the function. This will give you better encapsulation. If you learn to write your functions (and later classes) with passing in the resources and data you need (a practice known as "dependency injection"), you'll find you have cleaner and more maintainable code. Here's the example:
function getmotd($db, $user) {
$query = "SELECT cid FROM users WHERE id = " . (int)$user;
$result = mysql_query($query, $db);
/.../
}
$connect = mysql_connect(...);
mysql_select_db(...);
$motd = getmotd($connect, $user);
Hope this helps.
Use the global keyword.
Example
function getmotd($user) {
global $connect;
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
You can also do it like this
function getmotd($user) {
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $GLOBALS['connect']); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
If you want to make re-usable codes, you'd probably be better off with OOP. Create a class for the database, and add some properties for the database info, and access them from the functions by using the this keyword.

Categories