php cannot work with a substring - php

I`m making a php file to generate users and inserting them in a database. The first thing I made is to obtain the latest one and save it in a variable, then, I use a function to obtain the integer part of the string and increment that value by one, but that is the part that I think is not working.
This is the code:
<?php
$con = new mysqli('localhost', 'root', '', 'prueba');
function create_user($var){
$prefix = "U";
for($i = 0; $i < 5- strlen((String)$var); $i++) {
$prefix .= '0';
}
$var = mb_substr($var, 1);
if(is_numeric($var)) {
$int = $var++;
$var = $prefix . $int;
}
return $var;
}
$execute = mysqli_query($con, "select id_user from usuarios
WHERE id_user=(SELECT MAX(id_user) FROM usuarios)");
$row = mysqli_fetch_array($execute);
print_r($row['id_user']);
$var1 = $row['id_user'];
$userid=create_user($var1);
mysqli_query($con, "insert into usuarios (password, descripcion, id_user)
values ('A12345a', 'hgfhdgfh', ' $userid' )");
echo "hecho";
?>
Any help, please?

Change this line:
$int = $var++;
to:
$int = ++$var;
It's assigning the value of $var before incrementing.

Related

How to insert data from a PHP Array to MySQL

I am trying to insert data from an Array to MySQL Database. The Database contains two columns (string). Here is the code I wrote. What is wrong?
<?php
$time = date("H:i:s");
$a = array("foo", "bar", "hallo", "world");
//convert values of the array to string
$a = array_map('strval', $a);
//get array size
$arraySize = count($a);
//connection to database
$link = mysql_connect('', '', '') or die('connection lost');
mysql_select_db() or die('DB not found');
//try to insert data from the array to the database
for ($i = 0; $i < $arraySize; $i++) {
mysql_query("INSERT INTO `` (`time`, `text`) VALUES ('$time','$a[i]'))");
}
mysql_close($link);
?>
I cleared some personal data in the code intentionally.
Here is your answer..! Hope it works for you
$contentArray = [];
$rows = array();
$time = date("H:i:s");
$rows[] = array( "foo", "bar", "hallo", "world");
$fields = json_encode($rows);
array_push($contentArray,$fields,$time);
$values[] = '(' . placeholders('?', 2) . ')';
$field_names = "text,time";
$sql = "INSERT INTO table_name (" . $field_names . ") VALUES " . implode(',', $values);
Try this
remove the $a = array_map('strval',$a)
for(){
inside the for loop
$value = (string)$a[i];
$sql = "INSERT INTO $tablename (time,text) VALUES ('$time', '{$value}') ";
mysql_query($sql);
$value = "";
}
The problem is with this part of code:
VALUES ('$time','$a[i]')
I missed $ before i.
Also this part of code may be droped without any problems:
$a = array_map('strval', $a);

MySQL query variable not accepted

I am working on a PHP script that should get data from MySQL.
Here is what am I doing:
<?php
include('db.php');
session_start();
$doctor_actual=$_SESSION['doctor_actual'];
echo $doctor_actual;
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit,$adjacent);
}
function showData($data,$con,$limit,$adjacent){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "select * from tb_opiniones_doctor where codigo_verificacion = '".$doctor_actual."' order by id_opinion_doctor asc";
$rows = $con->query($sql);
$rows = $rows->num_rows;
$sql = "select * from tb_opiniones_doctor where codigo_verificacion = '".$doctor_actual."' order by id_opinion_doctor asc limit $start,$limit";
$data = $con->query($sql);
$str='<table><tr class="head"><td>Id</td><td>Firstname</td><td>Lastname</td></tr>';
if($data->num_rows>0){
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
$str.="<tr><td>".$row['id_opinion_doctor']."</td><td>".$row['id_opinion_doctor']."</td><td>".$row['id_opinion_doctor']."</td></tr>";
}
}else{
$str .= "<td colspan='5'>No Data Available</td>";
}
$str.='</table>';
echo $str;
pagination($limit,$adjacent,$rows,$page);
}
My problems are at the two queries, they only work if I put the real value for $doctor_actual, not as variable.
I have echoed the value for $doctor_actual, it is 9dv2ACvtwn2.
If I put in the queries ..where codigo_verificacion = "9dv2ACvtwn2"... the queries work fine.
If I put:
codigo_verificacion = '".$doctor_actual."'
or
codigo_verificacion = '.$doctor_actual.'
or
codigo_verificacion = $doctor_actual
it shows the message:
No Data Available
You should read about Variable scope. $doctor_actual outside function and $doctor_actual inside function are two different variables. As you can read above something like that
<?php
$var = 'text';
function myFunc()
{
global $var;
echo $var; // 'text'
}
will solve your problem.
But as noticed #Sean in comments below it's better idea to pass value as a parameter. Just add additional parameter to your function and pass value during function call.

Do-while loop hangs the connection to website

I am trying to use do-while loop to check if a value exists in database,
function check($a) {
$query = "SELECT * FROM `table` WHERE code = '$a'";
$result = mysql_query($query);
$nm = mysql_num_rows($result);
if ($nm > 0) {
return true;
} else {
return false;
}
}
function randomnumber() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 10) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$number = randomnumber();
do { $number = randomnumber(); } while (!check($number));
That codes somehow hangs the connection to website. After i execute this page, strangely it cannot connects to website until i restart the browser.
What may cause this ?
your query is never evaluating to true, so the loop is infinite. As long as it's not pulling back any rows where code = 'yourRandomNumber', then you will be looping indefinitely.
If you want to simply select a random 'code' from your database this code will be much more efficient than what you've got.
$query = 'SELECT DISTINCT code FROM `table`';
$result = mysql_query($query);
$my_arr = array();
while($row = $mysql_fetch_assoc($result)) {
$my_arr[] = $row['code']
}
$random_key = $my_arr[array_rand($my_arr)];
Re-reading your question and comments I'm less and less sure what your code originally set out to accomplish, if you could be a bit more clear on your objective here we could probably give you some advice on how to accomplish your goal more efficiently.
Edit:
This code will retrieve all of the codes already used in your table, calculate the difference from the possible codes, and then return one random unused code. No loop required. [well one loop, but it's a short one]
$psbl_codes = str_split("abcdefghijkmnopqrstuvwxyz023456789");
$query = 'SELECT DISTINCT code FROM `table`';
$result = mysql_query($query);
$used_codes = array();
while($row = $mysql_fetch_assoc($result)) {
$used_codes[] = $row['code']
}
$unused_codes = array_diff($psbl_codes, $used_codes);
echo "random unused code: " . $unused_codes[array_rand($unused_codes)];

Casting Issue with PHP MYSQL Combination

I think I have a problem with casting.
$db = mysqli_connect('127.0.0.1','root','password','test');
if (! $db) { die("Can't connect: " . mysqli_connect_error( )); }
$new_table = $_POST["newtablename"];
$old_table = $_POST["oldtablename"];
$numberRows = $_POST["numberrows"];
$startRow = $_POST["startrow"];
$counter = 0;
drop_table($db, $new_table);
create_table($db, $new_table);
for($counter = 0; $counter < $numberRows; $counter += 1)
{
$currentRow = getRow($db, $old_table);
$ID = $currentRow(1);
$Partner = $currentRow(2);
$Merchant = $currentRow(3);
}
function getRow($db, $old_table)
{
$select = "SELECT ID, Partner, Merchant FROM " .$old_table;
$q = mysqli_query($db, $select);
$row = mysqli_fetch_row($q);
return $row;
}
function create_table($db, $new_table){
$create = "CREATE TABLE " .$new_table. "(ID INT, Partner VARCHAR(20), Merchant VARCHAR(30))";
$q = mysqli_query($db, $create);
}
function drop_table($db,$new_table){
$drop = "DROP TABLE IF EXISTS " .$new_table;
$q = mysqli_query($db, $drop);
}
This is the error I get
Fatal error: Function name must be a string in C:\xampp\htdocs\myfiles\mysqli_combined_functions.php on line 26
Line 26 is where I set $ID = $currentRow(1). I am under the impression that the row will be returned as an array of variables, and using the proper number I can access the variable I want. Assuming thats true (let me know if its not) then I think it is reading the ID in the form of an INT which is what it is in the SQL table I have. Can someone help me cast it into string? or perhaps I'm missing the problem completely?
You use square brackets to access elements of arrays.
$currentRow[1]
Remember the first index will be 0 also.
Not casting. These are array indexes, note the square brackets. [ ]
$currentRow = getRow($db, $old_table);
$ID = $currentRow[1];
$Partner = $currentRow[2];
$Merchant = $currentRow[3];

php function with a while-loop

I have a function that generates a random combination.
my function looks like this:
function random_gen($length) {
$random= "";
srand((double)microtime()*1000000);
$char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$char_list .= "abcdefghijklmnopqrstuvwxyz";
$char_list .= "1234567890";
// Add the special characters to $char_list if needed
for($i = 0; $i < $length; $i++)
{
$random .= substr($char_list,(rand()%(strlen($char_list))), 1);
}
return $random;
}
$new_url = random_gen(6);
Now i would like to have a while-loop that checks if $new_url already exist in my database...
And then insert the result like this:
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
I got everything to work except the while-loop. and i just cant figure out how to do it...
define your code field as UNIQUE in your database
generate a code and run an INSERT
check with mysql_affected_rows() if the INSERT actually happened or not (i.e. code already present)
saves you a SELECT query
while ( true ) {
$new_url = random_gen(6);
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
if ( mysql_affected_rows() )
break;
}
Use this random_generator
function random_gen($length) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1];
}
return $string;
}
You don't need a while loop, just perform a query
mysql_query("SELECT COUNT(*) FROM lank WHERE code = {$new_url}");
It's pretty straight forward:
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
while($row['num'] > 0) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
}
This should work, without repeating code:
while(true) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if (!$row[0])
break;
}
Use the uniqid() function instead. It will always generate a random result.
If you need more security (i.e.: you don't want adjacent values), simply hash the output: sha1(uniqid()).

Categories